Linux Basic — Exit & Quit Handling
Exit & Quit Handling
Robust menu scripts trap interrupts and clean up temporary state. Common tasks: remove temp files, restore terminal settings, and save session state.
Basic Trap
cleanup() {
echo "cleaning up"
rm -f "$TMPFILE"
}
trap cleanup EXIT INT TERM
TMPFILE=$(mktemp)
trap ... EXIT always runs on normal exit and most signals. For finer control trap INT and TERM separately.
Restore Terminal State
If your menu changes stty (raw mode, echo off), always restore it in trap:
orig_stty=$(stty -g)
trap 'stty "$orig_stty"; cleanup' EXIT
stty -echo -icanon
Save State on Quit
When the user quits, serialise minimal state to ~/.mytoolstate so the next run resumes.
Next → Practice Exercises