Traps

When a process is running and in between we kill the process, the process terminates instantly without doing anything further. A programmer who writes a program may want to do some tasks before a program actually terminates; for example, a clean up of the temporary directories created, saving applications' state, saving logs, and so on. In such a case, a programmer would like to listen to signals and do the required task before actually allowing you to terminate the process.

Consider the following shell script example:

#!/bin/bash # Filename: my_app.sh # Description: Reverse a file echo "Enter file to be reversed" read filename tmpfile="/tmp/tmpfile.txt" # tac command is used to print a file in reverse order tac $filename > $tmpfile cp $tmpfile ...

Get Linux Shell Scripting Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.