Signal Handling in Shell

Level 4122 keystrokes

trap registers commands to run when the shell receives a signal or exits. cleanup runs on EXIT, so "Cleaning up..." is printed after "Running..." when the script ends; Ctrl+C prints "Interrupted!".

Shell code

# Cleanup function to run when the script ends
1cleanup() {
2 echo "Cleaning up..."
# Remove the lock file; -f gives no error if it is missing
3 rm -f /tmp/myapp.lock
4}
# Run cleanup whenever the shell exits
5trap cleanup EXIT
# On INT (Ctrl+C) print a message instead of stopping the script
6trap 'echo Interrupted!' INT
# Normal work; when the script ends, the EXIT trap prints Cleaning up...
7echo "Running..."

Output

Running...
Cleaning up...
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • .× 7
  • "× 4
  • '× 2
  • /× 2
  • -× 1
  • !× 1
  • (× 1
  • )× 1
  • {× 1
  • }× 1

More Shell examples at level 4

← Shell typing practice