程式扎記: [Linux 常見問題] Automatic exit from bash shell script on error

標籤

2015年2月1日 星期日

[Linux 常見問題] Automatic exit from bash shell script on error

Source From Here
Question:
I've been writing some shell script and I would find it useful if there was the ability to halt the execution of said shell script if any of the commands failed. See below shell script for an example:
- test.sh
  1. #!/bin/sh  
  2. #set -e  
  3.   
  4. doTesting()  
  5. {  
  6.     touch "Done"  
  7. }  
  8.   
  9. chkResult()  
  10. {  
  11.     [ -e "Done" ] && touch "Done2"  
  12. }  
  13.   
  14. rm -f Done*  
  15. rm -f Error*  
  16. echo "Running Testing..."  
  17.   
  18. doTesting  
  19. chkResult  
  20.   
  21. touch "Done3"  
  22. echo "Bye"  
If I execute this shell script and the result will be:
$ ./test.sh
Running Testing...
Bye

$ ls Done*
Done Done2 Done3

If we modify the test.sh on doTesting() to touch "Error" and execute it:
$ ./test.sh
Running Testing...
Bye

$ ls
Done3 Error test.sh

Here we don't expect Done3 to be generated while Done doesn't exist. Is there a global setting to make the script exit if one of the commands fails?

How-To
Use the set -e builtin:
  1. #!/bin/bash  
  2. set -e  
  3. # Any subsequent(*) commands which fail will cause the shell script to exit immediately  
Alternatively, you can pass -e on the command line:
$ bash -e test.sh
Running Testing...
$ ls
Error test.sh

Note.
The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in an ifstatement, part of a && or || list, or if the command's return value is being inverted via !

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!