Whamcloud - gitweb
b=21457
[fs/lustre-release.git] / build / exit_traps.sh
1 #!/bin/bash
2
3 # a framework for stacking EXIT traps
4 # this could, should be further enhanced to allow stacks of traps for various
5 # exits.  but right now it's hard-coded for EXIT traps
6
7 exit_actions=()
8
9 push_exit_trap() {
10     local action="$1"
11     local trap_handle="$2"
12
13     local var="exit_trap_handle_$trap_handle"
14
15     if [ -n "${!var}" ]; then
16         echo "fail!  trap handle $trap_handle is already in use"
17         return 1
18     fi
19
20     local num_items=${#exit_actions[@]}
21     exit_actions[$num_items]="$action"
22     eval $var="$num_items"
23
24     return 0
25
26 }
27
28 delete_exit_trap() {
29     local trap_handle="$1"
30
31     local var="exit_trap_handle_$trap_handle"
32     local trap_num=${!var}
33     exit_actions[$trap_num]=""
34     eval unset $var
35 }
36
37 print_exit_traps() {
38
39     local i num_items=${#exit_actions[@]}
40     for i in $(seq 0 $((num_items-1))); do
41         if [ -z "${exit_actions[$i]}" ]; then
42             continue
43         fi
44         echo "${exit_actions[$i]}"
45     done
46
47 }
48
49 run_exit_traps() {
50
51     local i num_items=${#exit_actions[@]}
52     for i in $(seq $((num_items-1)) -1 0); do
53         if [ -z "${exit_actions[$i]}" ]; then
54             continue
55         fi
56         eval ${exit_actions[$i]}
57     done
58
59 }
60
61 trap run_exit_traps EXIT
62
63 #if ! push_exit_trap "echo \"this is the first trap\"" "a"; then
64 #    echo "failed to install trap 1"
65 #    exit 1
66 #fi
67 #if ! push_exit_trap "echo \"this is the second trap\"" "b"; then
68 #    echo "failed to install trap 2"
69 #    exit 2
70 #fi
71 #delete_exit_trap "b"
72 #if ! push_exit_trap "echo \"this is the third trap\"" "b"; then
73 #    echo "failed to install trap 3"
74 #    exit 3
75 #fi
76
77 # to see the traps
78 #print_exit_traps