Using the trap command in Linux bash script

May 1, 2021

Comments

Adsense

Adsense

Adsense

Adsense

If a signal or software interrupt is generated while the script is running, then we can define what action is performed by that interrupt handler using the trap command. The trap command helps us in re-assigning the system response to a particular signal through the user-defined function or commands.

The syntax to use the trap command is either of the following:

$ trap 'command; command' signal-name
$ trap 'command; command' signal-number

The usage as per the preceding syntax is as follows:

trap 'echo "You pressed Control key" '  0 1 2 15

This will print the message You pressed Control key, when any of the signals SIGINTSIGHUP, or SIGTERM are received by the process:

trap 'rm file.tmp; echo "file.tmp is deleted" ' INT TERM HUP

When any of the SIGINT, SIGTERM, or SIGHUP signals arrive, then they will delete the file.tmp file and print the message.

While using the trap command, if the command string is surrounded by double quotes, then the command substitution and variable substitution will be done during the trap command execution. If the command string is enclosed in single quotes then the command substitution and variable substitution will be done when the signal is detected.

Satish Kumar

Satish Kumar

I am Satish Kumar, Founder of LinuxConcept. Linux and F.O.S.S enthusiast, love to work on open source platform and technologies.

Adsense

Adsense

Adsense

Adsense

Adsense

Adsense

Adsense

Adsense

Adsense

Related Posts

Backup of files in Linux using command line

In IT or our day-to-day computer industry activities, taking backup is one of the most important activities. Previously, offices were required to keep important paper in a safe place; but if a fire breaks out, then everything is finished. In the digital world, taking...

Using awk in Linux

awk is a program that has its own programming language for performing data-processing and generating reports. The GNU version of awk is gawk. awk processes data, which can be received from a standard input, input file, or as the output of any other command or process....

0 Comments

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

twenty − 9 =

News & Updates

Join Our Newsletter

Adsense

Adsense

Adsense

Adsense