5

我有一个 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
4

4 回答 4

3

我不了解 tcsh,但是使用 bash,您可以使用它set -e来执行此操作。设置-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"
于 2010-06-14T23:24:39.033 回答
3

我们开始吧:生成一个新的 shell,使用 ';' 忽略第一个状态,它返回全部清除。

$SHELL -c 'cp file/that/might/not/exist . ; echo "good"'
于 2010-06-15T18:32:44.677 回答
2
mustsucceed || exit 1
mustbeignored || :
于 2010-06-14T23:28:40.160 回答
1

如果您不在乎它是否失败,请-e从您的 shebang 中删除。如果您查看过tcsh 文档,@Adam 的回答应该会为您提供提示。

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

cp dont_care       . >& /dev/null
cp still_dont_care . >& /dev/null || echo "not there"
cp must_be_there   . >& /dev/null || exit 1 # oh noes!
于 2010-06-15T02:29:58.487 回答