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

发布于 2024-09-05 20:15:01 字数 287 浏览 6 评论 0原文

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

I've got a tcsh shell script that I would like to stop with an error on nonzero status most of the time, but in some cases I want to ignore it. For example:

#!/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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

暗喜 2024-09-12 20:15:01

我不知道 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"

I don't know about tcsh, but with bash, you can use set -e to do this. When the -e flag is set, bash will exit immediately if any subcommand fails (see the manual for technical details). When not set, it will continue to execute. So, you can do something like this:

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"
相权↑美人 2024-09-12 20:15:01

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

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

Here we go: Spawn a new shell, use ';' to ignore the first status, and it returns all clear.

$SHELL -c 'cp file/that/might/not/exist . ; echo "good"'
无边思念无边月 2024-09-12 20:15:01
mustsucceed || exit 1
mustbeignored || :
mustsucceed || exit 1
mustbeignored || :
知足的幸福 2024-09-12 20:15:01

如果您不在乎它是否失败,请从 shebang 中删除 -e 。如果您查看了 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!

If you don't care if it fails, remove the -e from your shebang. @Adam's answer ought to have provided a hint to you if you had looked at the tcsh documentation.

Also, you can throw away the error message:

cp dont_care       . >& /dev/null
cp still_dont_care . >& /dev/null || echo "not there"
cp must_be_there   . >& /dev/null || exit 1 # oh noes!
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文