2014-05-01 99 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