当前位置:   article > 正文

Bash 'trap'命令讲解_bash trap

bash trap

当我们运行一个Bash脚本,按下'Ctrl+c'去终止,通常脚本立即停止。但是我们可以在脚本中用‘trap’去捕捉这个信号,进行一部分处理。这是trap的应用场景。

'trap‘就是用来捕捉信号并进行相应的操作。有点类似于,其他程序中,抛出特定异常,异常会被捕捉到并会被有针对性的处理一样。

让我们模拟我们提到的'trap'的场景:

  1. $ cat try_bash_trap.sh
  2. #!/bin/bash
  3. set -ex -o pipefail
  4. trap 'cleanup' 2
  5. cleanup(){
  6. echo "---> Caught signals and Let us do clean-ups"
  7. rm -rf /tmp/temp_*.$$
  8. exit 2
  9. }
  10. for i in {1..100}
  11. do
  12. sleep 2
  13. touch /tmp/temp_${i}.$$
  14. done
  15. $ ./try_bash_trap.sh
  16. + trap cleanup 2
  17. + for i in '{1..100}'
  18. + sleep 2
  19. + touch /tmp/temp_1.28167
  20. + for i in '{1..100}'
  21. + sleep 2
  22. + touch /tmp/temp_2.28167
  23. + for i in '{1..100}'
  24. + sleep 2
  25. + touch /tmp/temp_3.28167
  26. + for i in '{1..100}'
  27. + sleep 2
  28. + touch /tmp/temp_4.28167
  29. + for i in '{1..100}'
  30. + sleep 2
  31. + touch /tmp/temp_5.28167
  32. + for i in '{1..100}'
  33. + sleep 2
  34. + touch /tmp/temp_6.28167
  35. + for i in '{1..100}'
  36. + sleep 2
  37. + touch /tmp/temp_7.28167
  38. + for i in '{1..100}'
  39. + sleep 2
  40. ^C++ cleanup
  41. ++ echo '---> Caught signals and Let us do clean-ups'
  42. ---> Caught signals and Let us do clean-ups
  43. ++ 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
  44. ++ exit 2
  45. $ echo $?
  46. 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:

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/197510
推荐阅读
相关标签
  

闽ICP备14008679号