2014-05-01 101 views
2

下面的腳本與-e選項運行,所以如果在它的命令失敗,那麼將退出:如何避免shell腳本失敗退出的特定命令

#!/bin/sh -e 
command1 #script should fail if command1 fails 
command2 #script should NOT fail if command2 fails 
command3 #script should fail if command3 fails 

我怎樣才能使腳本不是command2上失敗?

回答

7
command1 
command2 || true 
command3 
3

可以根據實際需要可以關閉該設置:

#!/bin/sh 
set -e 

command1 #script should fail if command1 fails 

set +e 
command2 #script should NOT fail if command2 fails 
set -e 

command3 #script should fail if command3 fails 
+0

這是尷尬。 – Sigi

+2

在某些情況下可能有必要(可能需要根據'command2'的確切退出狀態採取不同的操作)。 – chepner