Setting up traps in Shell Script

Imagine never again scrambling to manually clean up after an aborted script. The trap command in Linux grants you ultimate control, allowing you to define custom actions that execute on specific signals like Ctrl+C or script termination. No more unfinished tasks, no more panic – just zen-like peace of mind knowing your scripts will always leave things tidy. Let’s unlock the power of trap and transform your scripting experience! As a Linux administrator my day to day task involves a lot of scripting. And this scripts sometime needs to run clean-up jobs after the script finishes. Trap command in Linux is specifically designed to this task. Linux ‘trap‘ command sets up a trap to execute specific actions upon receiving the specific signal.

Let’s learn by example

1. Cleanup on Exit

#!/bin/bash
cleanup() {
    echo "Cleaning up before exit..."
    # Additional cleanup commands here
}

trap cleanup EXIT

# Rest of the script
echo "Script is running..."

if you run the script,

$ bash cleanupTrap.sh
Script is running...
Cleaning up before exit...

as you can see echo command gets executed first and upon completion of the script trap command gets triggered due to EXIT signal of the script which executes cleanup function.

2. Setting trap with other signal

here is the script otherSignal.sh

#!/bin/bash

cleanup() {
    echo "Cleaning up before exit..."
    # Additional cleanup commands here
}

trap cleanup EXIT SIGHUP SIGINT SIGTERM

# Rest of the script
echo "Script is running..."

Running otherSignal.sh

$ bash otherSignal.sh
Script is running...
Cleaning up before exit...

Here, the cleanup function is also triggered if the script receives signals like HUP, INT, or TERM.

3. Custom Signal Handling:

Here is script named customSignal.sh

#!/bin/bash

custom_handler() {
    echo "Custom handling for signal SIGUSR1"
    # Additional actions for the custom signal
}

trap custom_handler SIGUSR1

# Rest of the script
echo "Script is running..."

If you run the script,

$ bash customSignal.sh
Script is running...

As you can see because the script ends with EXIT signal, there was no custom signal found. That’s why the function custom_handler didn’t get executed as the trap was not triggered.

Now to execute the trap, you would have to add another line at the end of the script that would trigger it.

Let’s add the magic line into the script

#!/bin/bash

custom_handler() {
    echo "Custom handling for signal SIGUSR1"
    # Additional actions for the custom signal
}

trap custom_handler SIGUSR1

# Rest of the script
echo "Script is running..."

# Trigger the custom signal 
kill -s SIGUSR1 $$

Now if you run the script again,

$ bash customSignal.sh
Script is running...
Custom handling for signal SIGUSR1

as you can see, the line ‘kill -s SIGUSR1 $$‘  sends a custom signal which triggered the trap.

4. Using trap command multiple time in a single script

One question might come to your mind now, can the trap command be used in a script only once ? After example 3, it should be clear that trap command can be used as per your needs or multiple times in a shell script.

Here is a example of that, this is a script called multiTrap.sh

#!/bin/bash

cleanup_exit() {
    echo "Cleaning up on script exit..."
}

custom_handler() {
    echo "Custom handling for signal SIGUSR1"
}

# Set up trap for cleaning up on exit
trap cleanup_exit EXIT

# Set up trap for custom signal handling
trap custom_handler SIGUSR1

# Rest of the script
echo "Script is running..."

# Simulating script activities

# Trigger the custom signal
kill -s SIGUSR1 $$

# Rest of the script
echo "Script continues..."

if you run the script,

$ bash multiTrap.sh
Script is running...
Custom handling for signal SIGUSR1
Script continues...
Cleaning up on script exit...

As you can see, step by step
first the echo command gets executed ;
then custom signal is raised which triggers the second trap and that function custom_handler gets executed;
Then the second echo command with the string ‘Script continues…‘ gets executed ;
and finally as the script finishes it raises the EXIT command which triggers our first trap and cleanup_exit function gets executed.

In this example, the script sets up two traps: one for cleaning up on exit (EXIT signal) and another for handling a custom signal (SIGUSR1). You can customize and use the trap command multiple times based on your script’s requirements.

 

Congratulations, you’ve unlocked the power of the trap command! No more scrambling after aborted scripts, no more panic – just the zen-like calm of knowing your system will always be tidy. You’ve mastered:

  • Automatic clean-up: Say goodbye to unfinished tasks. Trap those pesky signals like Ctrl+C and script termination, triggering custom routines that keep your system pristine.
  • Custom signal handling: Go beyond the basics. Define unique actions for specific signals, giving your scripts superhuman awareness and responsiveness.
  • Multiple trap power: Need double the zen? No problem! Use multiple traps within a single script, tailoring each to tackle different situations with laser precision.

Remember, the trap command is your loyal digital butler, ready to handle the messy chores while you focus on what matters. Embrace its power, experiment with its flexibility, and watch your scripts blossom into clean, robust masterpieces.

Bonus Tip: Share your newfound zen! Teach others the magic of trap and spread the peace of tidy scripts across the scripting universe.

 

 

 

 

 

 

Leave a Reply