linux – 是什么意思!在shell中的命令之前?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了linux – 是什么意思!在shell中的命令之前?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2364字,纯文字阅读大概需要4分钟。
内容图文
问题出在标题中.以感叹号开头的shell命令(shell脚本的一部分)的目的是什么?具体例子:
在foo.sh中:
#!/usr/bin/env bash
set -e
! docker stop foo
! docker rm -f foo
# ... other stuff
我知道如果没有这个空间,感叹号就会用于历史替换! <表达>根据man page可用于评估“如果expr为假则为真”.但是在对我来说没有意义的示例上下文中.
解决方法:
TL; DR:这只是在您使用它的特定行中绕过set -e标志.
添加添加到hek2mgl’s correct and useful answer.
你有:
set -e
! command
Bash Reference Manual → Pipelines描述:
Each command in a pipeline is executed in its own subshell. The exit status of a pipeline is the exit status of the last command in the pipeline (…). If the reserved word ‘!’ precedes the pipeline, the exit status is the logical negation of the exit status as described above. The shell waits for all commands in the pipeline to terminate before returning a value.
这意味着 !在命令之前否定它的退出状态:
$echo 23
23
$echo $?
0
# But
$! echo 23
23
$echo $?
1
要么:
$echo 23 && echo "true" || echo "fail"
23
true
$! echo 23 && echo "true" || echo "fail"
23
fail
退出状态在很多方面都很有用.在脚本中,与set -e一起使用,只要命令返回非零状态,脚本就会退出.
因此,当你有:
set -e
command1
command2
如果command1返回非零状态,则脚本将完成,并且不会继续执行command2.
但是,还有一个值得一提的地方,在4.3.1 The Set Builtin中描述:
-e
Exit immediately if a pipeline (see Pipelines), which may consist of a single simple command (see Simple Commands), a list (see Lists), or a compound command (see Compound Commands) returns a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command’s return status is being inverted with !. If a compound command other than a subshell returns a non-zero status because a command failed while -e was being ignored, the shell does not exit. A trap on ERR, if set, is executed before the shell exits.
考虑到所有这些因素,当您有:
set -e
! command1
command2
你正在做的是绕过command1中的set -e标志.为什么?
>如果command1正常运行,它将返回零状态. !否定它,但设置-e不会触发退出,因为它来自与!反转的返回状态,如上所述.
>如果command1失败,它将返回非零状态. !将否定它,所以该行最终将返回零状态,脚本将继续正常.
内容总结
以上是互联网集市为您收集整理的linux – 是什么意思!在shell中的命令之前?全部内容,希望文章能够帮你解决linux – 是什么意思!在shell中的命令之前?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。