Bash Trap Command

LinuxLinuxBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the trap command in Bash scripting. The trap command is a powerful tool that allows you to catch and handle signals, interruptions, and user inputs in your scripts. By using trap, you can define specific actions to be taken when particular signals are received, enabling you to manage unpredictable behavior and gracefully handle various scenarios. This lab is designed for beginners and will guide you through the process of using the trap command effectively.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/BasicSystemCommandsGroup(["`Basic System Commands`"]) linux(("`Linux`")) -.-> linux/FileandDirectoryManagementGroup(["`File and Directory Management`"]) linux(("`Linux`")) -.-> linux/BasicFileOperationsGroup(["`Basic File Operations`"]) shell(("`Shell`")) -.-> shell/BasicSyntaxandStructureGroup(["`Basic Syntax and Structure`"]) shell(("`Shell`")) -.-> shell/ControlFlowGroup(["`Control Flow`"]) shell(("`Shell`")) -.-> shell/FunctionsandScopeGroup(["`Functions and Scope`"]) shell(("`Shell`")) -.-> shell/SystemInteractionandConfigurationGroup(["`System Interaction and Configuration`"]) linux/BasicSystemCommandsGroup -.-> linux/echo("`Text Display`") linux/FileandDirectoryManagementGroup -.-> linux/cd("`Directory Changing`") linux/BasicFileOperationsGroup -.-> linux/touch("`File Creating/Updating`") linux/BasicFileOperationsGroup -.-> linux/chmod("`Permission Modifying`") shell/BasicSyntaxandStructureGroup -.-> shell/shebang("`Shebang`") shell/BasicSyntaxandStructureGroup -.-> shell/comments("`Comments`") shell/ControlFlowGroup -.-> shell/while_loops("`While Loops`") shell/FunctionsandScopeGroup -.-> shell/func_def("`Function Definition`") shell/SystemInteractionandConfigurationGroup -.-> shell/trap_statements("`Trap Statements`") subgraph Lab Skills linux/echo -.-> lab-385392{{"`Bash Trap Command`"}} linux/cd -.-> lab-385392{{"`Bash Trap Command`"}} linux/touch -.-> lab-385392{{"`Bash Trap Command`"}} linux/chmod -.-> lab-385392{{"`Bash Trap Command`"}} shell/shebang -.-> lab-385392{{"`Bash Trap Command`"}} shell/comments -.-> lab-385392{{"`Bash Trap Command`"}} shell/while_loops -.-> lab-385392{{"`Bash Trap Command`"}} shell/func_def -.-> lab-385392{{"`Bash Trap Command`"}} shell/trap_statements -.-> lab-385392{{"`Bash Trap Command`"}} end

Create a Bash Script

Let's start by creating a new Bash script file where we'll implement the trap command.

  1. Open a terminal in the WebIDE. You should see a prompt ending with a $ symbol.

  2. Navigate to the project directory:

    cd ~/project

    This command changes your current working directory to /home/labex/project.

  3. Create a new file named trap_example.sh:

    touch trap_example.sh

    The touch command creates an empty file if it doesn't exist, or updates the modification time if it does.

  4. Open the trap_example.sh file in the WebIDE editor. You can do this by clicking on the file name in the file explorer on the left side of the WebIDE.

Implement a Basic Trap Command

Now, let's implement a basic trap command in our script to catch specific signals and exit gracefully.

  1. Add the following content to the trap_example.sh file:

    #!/bin/bash
    
    cleanup_and_exit() {
      echo -e "\nSignal received! Cleaning up and exiting..."
      exit 0
    }
    
    trap cleanup_and_exit SIGINT SIGTERM
    
    echo "This script will run until you press Ctrl+C."
    echo "Press Ctrl+C to see the trap in action and exit gracefully."
    
    count=1
    while true; do
      echo "Script is running... (iteration $count)"
      sleep 1
      ((count++))
    done

    Let's break down this script:

    • The first line #!/bin/bash is called a shebang. It tells the system that this script should be executed by the Bash shell.
    • We define a cleanup_and_exit function that prints a message and exits the script.
    • The trap command is set up to call cleanup_and_exit when it catches either SIGINT (interrupt) or SIGTERM (termination) signals. SIGINT is typically sent when you press Ctrl+C, while SIGTERM is often used when a process is asked to terminate gracefully.
    • The echo commands print instructions for the user.
    • The while loop runs indefinitely, printing a message and incrementing a counter every second.
  2. Save the file after adding the content.

Make the Script Executable and Run It

Before we can run our script, we need to make it executable. This tells the system that this file is allowed to be run as a program.

  1. In the terminal, make the script executable:

    chmod +x ~/project/trap_example.sh

    The chmod command changes the permissions of a file. The +x option adds execute permission.

  2. Run the script:

    ~/project/trap_example.sh

    This command tells Bash to execute our script.

  3. The script will start running. You'll see the instructions printed on the screen. Let it run for a few seconds.

  4. Now, press Ctrl+C to interrupt it. You should see the message "Signal received!" before the script exits. This is our trap in action!

Modify the Trap to Use a Function

Instead of using a simple function, let's modify our script to use a more complex function with the trap command. This allows us to perform more detailed actions when a signal is received.

  1. Open the trap_example.sh file in the WebIDE editor.

  2. Replace the content of the file with the following:

    #!/bin/bash
    
    cleanup_and_exit() {
      echo -e "\nSignal received! Cleaning up..."
      echo "Performing cleanup tasks..."
      ## Add any necessary cleanup code here
      echo "Cleanup completed."
      echo "Exiting script gracefully."
      exit 0
    }
    
    trap cleanup_and_exit SIGINT SIGTERM
    
    echo "This script will run until you press Ctrl+C."
    echo "Press Ctrl+C to see the trap function in action and exit gracefully."
    
    count=1
    while true; do
      echo "Script is running... (iteration $count)"
      sleep 1
      ((count++))
    done

    Let's examine the changes:

    • We've expanded the cleanup_and_exit function to include more detailed messages and a placeholder for cleanup tasks.
    • The function now simulates a more realistic cleanup process, which could include tasks like closing file handles, removing temporary files, or releasing other resources.
    • We've updated the main loop to show an iteration count, making it clearer that the script is actively running.
  3. Save the file after making these changes.

  4. Run the script again and test it by pressing Ctrl+C:

    ~/project/trap_example.sh

    You should see the new messages from the cleanup_and_exit function when you interrupt the script, demonstrating a graceful exit.

Summary

In this lab, you learned how to use the trap command in Bash scripting. You created a script that catches specific signals and defines actions to be taken when those signals are received. You explored different ways of using the trap command, including using inline commands and functions.

The trap command is a powerful tool for handling interruptions and performing cleanup actions in your Bash scripts. It allows you to create more robust and user-friendly command-line applications by gracefully handling unexpected terminations and user interrupts.

Remember, the ability to handle signals can be crucial in many scripting scenarios, such as ensuring proper cleanup of temporary files, closing network connections, or saving state before a script exits unexpectedly.

Other Linux Tutorials you may like