The trap of Bash trap
Can you spot the problem with the following Bash script? resource_created="false" function cleanup() { echo "Exit code: $?" if [[ $resource_created == "true" ]]; then echo "Clean up resource" else echo "Nothing to clean up" fi } function main() { resource_created="true" echo "Resource created" exit 1 } trap cleanup EXIT main | tee /tmp/my.log The intent is that,we use global variable Resource created Exit code: 0 Nothing to clean up Why? The catch is with the pipe resource_created="false" function cleanup() { echo "Exit code: $?" if [[ $resource_created == "true" ]]; then echo "Clean up resource" else echo "Nothing to clean up" fi echo "cleanup() PID: $BASHPID" } function main() { echo "main() PID: $BASHPID" resource_created="true" echo "Resource created" exit 1 } trap cleanup EXIT echo "Bash PID: $BASHPID" main | tee /tmp/my.log Output: Bash PID: 9852 main() PID: 9853 Resource created Exit code: 0 Nothing to clean up cleanup() PID: 9852 Then if global variable and exit code don‘t work,how do we untangle? File! function cleanup() { if [[ -f /tmp/resource_created ]]; then echo "Exit code: $(cat /tmp/resource_created)" echo "Clean up resource" else echo "Nothing to clean up" fi } function main() { echo "Resource created" echo 1 >/tmp/resource_created exit 1 } trap cleanup EXIT main | tee /tmp/my.log Output: Resource created Exit code: 1 Clean up resource Okay,it is almost the end of this short blog post. Bash programming is tricky,watch out for the traps. Thanks for reading and happy coding! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |