Whamcloud - gitweb
b=22281 refactor packaging and versioning
[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_handles="$@"
30
31     local handle
32     for handle in $trap_handles; do
33         local var="exit_trap_handle_$handle"
34         local trap_num=${!var}
35         exit_actions[$trap_num]=""
36         eval unset $var
37     done
38 }
39
40 print_exit_traps() {
41
42     local i num_items=${#exit_actions[@]}
43     for i in $(seq 0 $((num_items-1))); do
44         if [ -z "${exit_actions[$i]}" ]; then
45             continue
46         fi
47         echo "${exit_actions[$i]}"
48     done
49
50 }
51
52 run_exit_traps() {
53
54     local i num_items=${#exit_actions[@]}
55     for i in $(seq $((num_items-1)) -1 0); do
56         if [ -z "${exit_actions[$i]}" ]; then
57             continue
58         fi
59         eval ${exit_actions[$i]}
60     done
61
62 }
63
64 trap run_exit_traps EXIT
65
66 if [ "$1" = "unit_test" ]; then
67     if ! push_exit_trap "echo \"this is the first trap\"" "a"; then
68         echo "failed to install trap 1"
69         exit 1
70     fi
71     if ! push_exit_trap "echo \"this is the second trap\"" "b"; then
72         echo "failed to install trap 2"
73         exit 2
74     fi
75     delete_exit_trap "b"
76     if ! push_exit_trap "echo \"this is the third trap\"" "b"; then
77         echo "failed to install trap 3"
78         exit 3
79     fi
80     
81     # to see the traps
82     print_exit_traps
83     echo "------------"
84
85     delete_exit_trap "a" "b"
86     print_exit_traps
87     echo "------------"
88    
89     if ! push_exit_trap "echo \"this is the first trap\"" "a"; then
90         echo "failed to install trap 1"
91         exit 1
92     fi
93     if ! push_exit_trap "echo \"this is the second trap\"" "b"; then
94         echo "failed to install trap 2"
95         exit 2
96     fi
97     if ! push_exit_trap "echo \"this is the third trap\"" "c"; then
98         echo "failed to install trap 3"
99         exit 3
100     fi
101     delete_exit_trap "a" "c"
102
103     print_exit_traps
104     echo "------------"
105 fi