4

I would like to know what exactly the trap command is and how it is used in the terminal.
I came across this in the command line help.

1

2 Answers 2

7

trap is not a external command, but a built-in command of bash. It can be used in a script to run a bash function when some event (like Ctrl+C, or a signal) is received by the script. For example, if you create a temporary file in the script, it is seen as best practice to remove it when the script finish. However, if the script is killed or interrupted, the end of the script will not be run, unless if that's handled by trap.

It doesn't serve much outside of a script, so you can safely ignore it.

And I would suggest to search "bash trap" to see various tutorials about programming and scripting explaining in details the usage.

2
  • yours looks nice. You included more text.
    – Raja G
    Jan 25, 2014 at 13:35
  • So trap is something like an conditional statement in programming ?waiting for a particular statement? And by scripts, you mean a special set of terminal commands?
    – CENTAUR
    Sep 24, 2014 at 16:50
2

AFAIK trap generally is used as a shell builtin which executes the command when the shell receives signals.

We can also use this ignore and clear leftover signals at some process interruption.

There some documents which can help you with trap:

You must log in to answer this question.

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