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}
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:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值