10

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?

17

From the bash manual:

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

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

  • 12
    Correct. In case a reader came here because of the question's title, note that this is the meaning of 0 in a shell trap command. When sending a signal with kill, a signal number of 0 means not to send a signal after all; this is a way of testing the existence of the target process. – Gilles Jul 24 '11 at 14:00
  • @Mat: Thanks a lot. I was reading man 1 trap... – Christoph Wurm Jul 24 '11 at 14:30
  • 1
    But it's not in the list output by trap -l! – amphetamachine Jul 25 '11 at 8:59
1

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
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.