What if your script could clean up after itself every time you stop it suddenly?
Why Signal handling with trap in Bash Scripting? - Purpose & Use Cases
Imagine you are running a long script in the terminal, and suddenly you need to stop it safely or clean up temporary files before exiting. Without any special setup, you just press Ctrl+C and hope nothing breaks.
Manually stopping scripts can leave your system messy or your data corrupted. You might forget to remove temporary files or close connections, causing errors later. It's slow and risky to handle these interruptions by hand every time.
Using trap in bash lets your script catch signals like Ctrl+C and run cleanup code automatically. This means your script can stop safely, remove temporary files, and leave things tidy without you doing anything extra.
echo 'Running...'; sleep 100; echo 'Done'
trap 'echo Cleanup; rm -f temp.txt; exit' INT; echo 'Running...'; sleep 100; echo 'Done'
You can make your scripts smart and safe by handling interruptions gracefully, avoiding errors and wasted time.
When downloading files or processing data, if you press Ctrl+C, the script can delete partial files and close connections properly, so you don't get broken or incomplete results.
Manual interruption can cause messy leftovers and errors.
trap lets scripts catch signals and run cleanup code.
This makes scripts safer and more reliable during unexpected stops.