2012-07-19 107 views
2

我知道,你可以使用shell腳本shortcutting布爾運算做某種異常處理,像這樣:「異常處理」 shell腳本

my_first_command && my_second_command && my_third_command 

但這很快就變成不可讀和不可維護的數您想鏈接的命令增長。如果我正在編寫一個腳本(或者一個shell函數),是否有一種很好的方法可以讓腳本或函數的執行停止在第一個非零的返回碼上,而不用寫在一個大行上?

(我用zsh,所以如果有答案,只有在zsh工作,通過我的罰款。)

回答

3

-e選項執行此操作:

ERR_EXIT (-e, ksh: -e) 
      If a command has a non-zero exit status, execute the ZERR trap, 
      if set, and exit. This is disabled while running initialization 
      scripts. 

你應該能夠在把這個shebang行,如:

#!/usr/bin/zsh -e 

大多數殼有這個選項,它通常被稱爲-e

+0

這是完美的 - 非常感謝!一旦不接受窗口過期,我會立即接受。 – 2012-07-20 00:11:37