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 0Create a
trap command to catch SIGINT and run a function called handle_interruptDefine a function called
handle_interrupt that prints "Interrupt caught! Exiting..." and exits the scriptCreate a
while loop that increments count every second and prints the current countPrint 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