Bash 'trap'命令讲解

发布时间:2018-12-28 14:23  浏览次数:36


当我们运行一个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} do sleep 2 touch /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:

标签

归档

阅读排行

支付宝搜索“559315787”,天天领红包