17

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?

3 Answers3

21

From the bash manual:

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

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

Mat
  • 52,586
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
slm
  • 369,824
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.

dbrower
  • 1,017