I have in a script

trap 'kill ${!}; term_handler' SIGTERM

So the SIGTERM is executed when we kill the pid ${!}

  • Better not using this form: ${!} but simply $! to avoid confusion with an attempt to use variable indirection, like man bash | less +/' possible to obtain the keys'/ Jun 1, 2020 at 19:32

3 Answers 3


The ${!} or better still, the $! should return the process ID (PID) of the last executed command.

! - Expands to the process ID of the most recently executed background (asynchronous) command, so $! would contain the process ID (PID) of the last job that was backgrounded.

It should be noted that this stands for programs started in the background. If no background processes have been started the parameter is not set.


$! or ${!} returns the process id of the last running process in the background.

ex: wait $! would wait for the last process to finish before continuing

trap 'kill ${!}; term_handler' SIGTERM

This says to run the shell commands kill ${!}; term_handler when the shell receives the signal SIGTERM. The ${!} is the special parameter $!, which

($!) Expands to the process ID of the job most recently placed into the background, whether executed as an asynchronous command or using the bg builtin

That would have the effect of killing the last (presumably only) background process started by the script if the script received SIGTERM, and then running term_handler, presumably some function. Without the trap, the background process might be left running after the main script ended.

Though the trap there is tied specifically to SIGTERM, e.g. SIGINT, SIGHUP or a normal termination would not trigger it. At least in Bash, one could use

trap 'kill ${!}; term_handler' EXIT

to run the trap when the script exits for any reason.

Not the answer you're looking for? Browse other questions tagged .