What is signal 0 in a trap command?

I’m following this guide on how to set up passwordless SSH authentication with ssh-agent.

To start up ssh-agent the author recommends the following code in .bash_profile:

SSHAGENT=/usr/bin/ssh-agent
SSHAGENTARGS="-s"
if [ -z "$SSH_AUTH_SOCK" -a -x "$SSHAGENT" ]; then
    eval `$SSHAGENT $SSHAGENTARGS`
    trap "kill $SSH_AGENT_PID" 0
fi

I don’t understand why it is trapping signal 0. According to man 7 signal there is no such signal.

Is this just a typo or bug or does this really achieve something?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

From the bash manual:

trap [-lp] [[arg] sigspec ...]

… If a sigspec is EXIT (0) the command arg is executed on exit from the shell.

Method 2

As @Mat shows in his answer, a SIGSPEC of 0, when used on the trap command will cause the trap command to run when the script exits.

This example illustrates what happens.

$ cat tr.bash 
#!/bin/bash

echo "PID: $$"

trap 'echo hi; exit 1' 0 1 2 15

while [ 1 ]; do
    sleep 3
done

When we run this:

$ ./tr.bash 
PID: 24086

It sits here waiting indefinitely. In another window if we now send kill signals to it you’ll see that a kill -0 will not kill the process, even though signal 0 is listed in the trap command.

$ kill -0 $(pgrep tr.bash)
$

However if we kill the script using signal 1, kill -1:

$ kill -1 $(pgrep tr.bash)
$

We’ll see that the script exits, and prints the message, “hi” 2 times. The first for signal 1, and the second because the script exited.

$ ./tr.bash 
PID: 24086
hi
hi

Method 3

trap on 0 is run when the shell exits. It is commonly used to clean up tmp files in one place that is always executed:

tmp=/tmp/myscript.$$

trap ‘rm -f $tmp; exit’ 0 1 2 15

do_a_bunch_of_stuff

exit

the exit at the end of the trap exits the shell at the cleanup with the right status.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x