|
|
|
The |
|
|
Basic trap syntax: trap ‘commands’ SIGNAL |
|
|
Trap EXIT runs when the script exits (any reason): |
|
|
Common signals to trap: EXIT (0) - Script exit (success or failure) INT (2) - Interrupt (Ctrl+C) TERM (15) - Termination request HUP (1) - Hangup ERR - On error (bash only) |
|
|
Trap for cleanup of temporary files: |
|
|
Multiple commands in trap: |
|
|
Reset or ignore a trap: |
|
|
Display current traps: |
|
|
Trap with signal number instead of name: |
|
|
Common pattern: cleanup function |
|
|
Trap preserves exit code: |
|
|
Combining multiple signals: |
|
|
Bash
Bash provides ERR trap for errors: |
|
|
DEBUG trap runs before each command: |
|
|
Practical example: Lock file with cleanup |
|
|
Trap in a loop (handle Ctrl+C gracefully): |
|
|
Best practice: Always trap EXIT for scripts that create temporary resources. |
|