本文主要是介绍Bash 'trap'命令讲解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
当我们运行一个Bash脚本,按下'Ctrl+c'去终止,通常脚本立即停止。但是我们可以在脚本中用‘trap’去捕捉这个信号,进行一部分处理。这是trap的应用场景。
'trap‘就是用来捕捉信号并进行相应的操作。有点类似于,其他程序中,抛出特定异常,异常会被捕捉到并会被有针对性的处理一样。
让我们模拟我们提到的'trap'的场景:
$ cat try_bash_trap.sh
#!/bin/bash
set -ex -o pipefail
trap 'cleanup' 2
cleanup(){echo "---> Caught signals and Let us do clean-ups"rm -rf /tmp/temp_*.$$exit 2
}
for i in {1..100}
dosleep 2touch /tmp/temp_${i}.$$
done
$ ./try_bash_trap.sh
+ trap cleanup 2
+ for i in '{1..100}'
+ sleep 2
+ touch /tmp/temp_1.28167
+ for i in '{1..100}'
+ sleep 2
+ touch /tmp/temp_2.28167
+ for i in '{1..100}'
+ sleep 2
+ touch /tmp/temp_3.28167
+ for i in '{1..100}'
+ sleep 2
+ touch /tmp/temp_4.28167
+ for i in '{1..100}'
+ sleep 2
+ touch /tmp/temp_5.28167
+ for i in '{1..100}'
+ sleep 2
+ touch /tmp/temp_6.28167
+ for i in '{1..100}'
+ sleep 2
+ touch /tmp/temp_7.28167
+ for i in '{1..100}'
+ sleep 2
^C++ cleanup
++ echo '---> Caught signals and Let us do clean-ups'
---> Caught signals and Let us do clean-ups
++ rm -rf /tmp/temp_1.28167 /tmp/temp_2.28167 /tmp/temp_3.28167 /tmp/temp_4.28167 /tmp/temp_5.28167 /tmp/temp_6.28167 /tmp/temp_7.28167
++ exit 2
$ echo $?
2
Trap is a simple, but very useful utility. If your script creates temporary files, such as this simple script which replaces FOO for BAR in all files in the current directory, /tmp is clean when the script exits. If it gets interrupted partway through, though, there could be a file lying around in /tmp:
这篇关于Bash 'trap'命令讲解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!