Unix 如何运行tcsh shell命令并有选择地忽略状态?

Unix 如何运行tcsh shell命令并有选择地忽略状态?,unix,shell,csh,tcsh,Unix,Shell,Csh,Tcsh,我有一个tcsh shell脚本,我想在大多数情况下以非零状态的错误停止它,但在某些情况下我想忽略它。例如: #!/bin/tcsh -vxef cp file/that/might/not/exist . #Want to ignore this status cp file/that/might/not/exist . ; echo "this doesn't work" cp file/that/must/exist . #Want to stop if this status is n

我有一个tcsh shell脚本,我想在大多数情况下以非零状态的错误停止它,但在某些情况下我想忽略它。例如:

#!/bin/tcsh -vxef

cp file/that/might/not/exist . #Want to ignore this status
cp file/that/might/not/exist . ; echo "this doesn't work"
cp file/that/must/exist . #Want to stop if this status is nonzero

我不知道tcsh,但是有了bash,您可以使用它来实现这一点。设置
-e
标志后,如果任何子命令失败,bash将立即退出(有关技术详细信息,请参阅手册)。未设置时,它将继续执行。所以,你可以这样做:

set +e
cp file/that/might/not/exist .  # Script will keep going, despite error
set -e
cp file/that/might/not/exist .  # Script will exit here
echo "This line is not reached"

如果您不在乎它是否失败,请从shebang中删除
-e
@亚当的回答应该给你一个提示,如果你看了这本书的话

此外,您还可以丢弃错误消息:

cp dont_care       . >& /dev/null
cp still_dont_care . >& /dev/null || echo "not there"
cp must_be_there   . >& /dev/null || exit 1 # oh noes!

我们开始:生成一个新的shell,使用“;”忽略第一个状态,并返回全部清除

$SHELL -c 'cp file/that/might/not/exist . ; echo "good"'

csh编程被认为是有害的。认真地我正在研究一个类似的问题。tcsh对待内置命令(如cd和limit)的方式似乎不同于外部命令(如false)。内置命令总是导致脚本终止,而不考虑-e。此外,“| | echo last command failed”也无法按预期工作。对于-e,| |之后的部分永远不会被调用。如果没有-e,| |之后的部分按预期调用,但是对于内置命令,您将在之后立即退出脚本。讨厌!大多数时候,我关心它是否失败。对于少数例外情况,我不在乎。只要
中有
e
/bin/tcsh-vxef
,出错时总是退出;这就是
e
所做的。您必须删除
e
才能获得任何其他行为``@沃尔特,那么当你调用shell时,你不能使用<代码> -e>代码> @ GelnJejman,正如他在这个问题的顶部所说的,他希望在大部分时间内停止一个非零状态的错误。“这就是为什么我们要用‘-e’上下文来做这件事。考虑用“”来替换“回声好”,以防止任何事情的回响。
$SHELL -c 'cp file/that/might/not/exist . ; echo "good"'