Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit after trap fires

Take this script

#!/bin/sh

fd ()
{
  echo Hello world
  exit
}

trap fd EXIT INT

for g in {1..5}
do
  echo foo
  sleep 1
done

I would like fd to fire once, either from Control-C or if the script exits normally. However if you hit Control-C it will run twice. How can I fix this?

like image 474
Zombo Avatar asked Jan 11 '13 09:01

Zombo


People also ask

What is trap exit?

The exit signal is a bash builtin and can be used to catch any signal. For all intents and purposes, if you trap exit, it will be executed when the shell process terminates. Exit the shell, returning a status of n to the shell's parent. If n is omitted, the exit status is that of the last command executed.

How do I exit bin bash?

One of the many known methods to exit a bash script while writing is the simple shortcut key, i.e., “Ctrl+X”. While at run time, you can exit the code using “Ctrl+Z”.

Does a bash script exit on error?

An exit status code is returned when any Linux command is executed from the terminal, either the command is successful or unsuccessful. This status code can be used to show the error message for unsuccessful execution or perform any particular task by using shell script.

How do you fail a shell script?

This can actually be done with a single line using the set builtin command with the -e option. Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code.


1 Answers

Do cascading traps. exit 127 will run the EXIT trap and set the exit code to 127, so you can say

#!/bin/sh

fd () {
  echo Hello world
  # No explicit exit here!
}

trap fd EXIT
trap 'exit 127' INT

I remember learning this from other people's scripts after struggling with various workarounds to your problem for several years. After that, I have noticed that some tutorials do explain this technique. But it is not documented clearly in e.g. the Bash manual page IMHO. (Or it wasn't when I needed it. Maybe some things don't change in 15 years ... :-)

like image 133
tripleee Avatar answered Oct 04 '22 19:10

tripleee