Bash · 1330 bytes Raw Blame History
1 #!/bin/sh
2 TEST_PREFIX="[trap]"
3 . "$(cd "$(dirname "$0")" && pwd)/test_harness.sh"
4
5 section "1. trap EXIT"
6 compare_output "trap EXIT runs on exit" 'trap "echo bye" EXIT; echo hello'
7 compare_output "trap EXIT runs after commands" 'trap "echo last" EXIT; echo first; echo second'
8 compare_output "trap EXIT with explicit exit" 'trap "echo cleanup" EXIT; echo running; exit 0'
9 compare_output "trap EXIT order" 'trap "echo bye" EXIT; echo a; echo b'
10
11 section "2. trap management"
12 compare_output "trap reset with dash" 'trap "echo caught" EXIT; trap - EXIT; echo done'
13 compare_output "trap empty string ignores" 'trap "" INT; echo ok'
14 check_exit "trap -l lists signals" 'trap -l' "0"
15 check_exit "trap -p prints current traps" 'trap -p' "0"
16 compare_output "trap -p shows set trap" 'trap "echo bye" EXIT; trap -p EXIT'
17
18 section "3. trap with signals"
19 compare_output "trap ERR on command failure" 'trap "echo error" ERR; false; true'
20 compare_output "trap multiple signals" 'trap "echo sig" EXIT; echo running'
21 compare_output "trap replaces previous" 'trap "echo first" EXIT; trap "echo second" EXIT; true'
22
23 section "4. trap in subshell"
24 compare_output "trap not inherited in subshell" 'trap "echo parent" EXIT; (echo child); echo back'
25 compare_output "trap in subshell independent" '(trap "echo sub_exit" EXIT; echo in_sub)'
26
27 print_summary