fac*_*ess 3 linux command-line test
当我按照下面的方式编写代码时,我可以在else语句后运行几个命令:
if [ "$?" -eq 0 ]
then
echo "OK"
else
echo "NOK"
exit 1
fi
Run Code Online (Sandbox Code Playgroud)
但是,当我使用另一种语法时,我无法在OR之后合并 2 个命令:
[ "$?" -eq 0 ] && echo "OK" || (echo "NOK" >&2 ; exit 1)
Run Code Online (Sandbox Code Playgroud)
在我的用例中,我有一个基于 的复杂脚本"$?" == 0,所以我正在寻找一种方法来在它不正确时中止(除了回显消息)。
这对( )产生了一个子shell,破坏了使用exit命令退出整个脚本的目标。
只需替换( )with { } (并调整语法,因为{ }不是自动分隔符,而是更像命令:后面{和最后一个命令内部的空格必须以某个终止符结尾:;fits):这将在同一个 shell 中运行内部的命令链,从而退出会影响这个外壳。
[ "$?" -eq 0 ] && echo "OK" || { echo "NOK" >&2; exit 1;}
Run Code Online (Sandbox Code Playgroud)
更新:@D.BenKnoble 评论说应该echo失败,行为不会像以前的if ...; then ... else ... fi构造。所以 firstecho的退出代码必须用 noop:命令“转义” (内置的不会失败)。
[ "$?" -eq 0 ] && { echo "OK"; :;} || { echo "NOK" >&2; exit 1;}
Run Code Online (Sandbox Code Playgroud)
参考:
POSIX :
分组命令
分组命令的格式如下:
Run Code Online (Sandbox Code Playgroud)(compound-list) Execute compound-list in a subshell environment; see Shell Execution Environment. Variable assignments and built-in commands that affect the environment shall not remain in effect after the list finishes.[...]
Run Code Online (Sandbox Code Playgroud){ compound-list;} Execute compound-list in the current process environment. The semicolon shown here is an example of a control operator delimiting the } reserved word. Other delimiters are possible, as shown in Shell Grammar; a <newline> is frequently used.
| 归档时间: |
|
| 查看次数: |
755 次 |
| 最近记录: |