0
0
Bash Scriptingscripting~30 mins

Signal handling with trap in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Signal handling with trap
📖 Scenario: You are writing a simple bash script that runs a loop and waits for user interruption. You want to handle the interrupt signal gracefully to clean up before exiting.
🎯 Goal: Build a bash script that uses trap to catch the SIGINT signal (Ctrl+C) and print a friendly message before exiting.
📋 What You'll Learn
Create a variable called count and set it to 0
Create a trap command to catch SIGINT and run a function called handle_interrupt
Define a function called handle_interrupt that prints "Interrupt caught! Exiting..." and exits the script
Create a while loop that increments count every second and prints the current count
Print the final message when the script is interrupted
💡 Why This Matters
🌍 Real World
Signal handling is important in scripts that run continuously or wait for user input. It helps to clean up resources or save state before the script stops.
💼 Career
Many system administration and automation tasks require writing scripts that handle signals to avoid abrupt termination and data loss.
Progress0 / 4 steps
1
Create a counter variable
Create a variable called count and set it to 0.
Bash Scripting
Need a hint?

Use count=0 to create the variable.

2
Set up the trap for SIGINT
Create a trap command to catch the SIGINT signal and run a function called handle_interrupt.
Bash Scripting
Need a hint?

Use trap handle_interrupt SIGINT to catch Ctrl+C.

3
Define the interrupt handler function
Define a function called handle_interrupt that prints "Interrupt caught! Exiting..." and exits the script.
Bash Scripting
Need a hint?

Define the function with handle_interrupt() { ... } and use echo and exit 0.

4
Create the counting loop and print output
Create a while loop that increments count every second and prints the current count using echo. The script should run until interrupted. The output should show the count numbers starting from 1.
Bash Scripting
Need a hint?

Use while true; do ... done, increment count with count=$((count + 1)), print with echo, and pause with sleep 1.