我有一个bash脚本,其命令我链接在一起&&,因为我希望脚本停止,如果单个步骤失败.
其中一个步骤基于heredoc创建配置文件:
some_command &&
some_command &&
some_command &&
some_command &&
some_command &&
some_command &&
cat > ./my-conf.yml <<-EOF
host: myhost.example.com
... blah blah ...
EOF
... lots more commands ...
Run Code Online (Sandbox Code Playgroud)
如何在&&链中包含此命令?我试过了:
&&在EOF之后立即放置.不起作用,因为EOF必须独立.&&按照EOF 放置在一条线上.不行,因为bash认为我正在尝试&&用作命令.&&在>重定向器之前.没有用,因为重定向器在逻辑上是命令的一部分&&.澄清:
在从heredoc生成配置文件的命令后面有很多(多行)命令,所以理想情况下我正在寻找一个允许我在heredoc之后放置以下命令的解决方案,这是脚本的自然流程.那就是我不希望在一行上内联20多个命令.
who*_*oan 36
您可以将控制操作符 放在此文档中&&的EOF单词后面,并且可以链接多个命令:
cat > file <<-EOF && echo -n "hello " && echo world
Run Code Online (Sandbox Code Playgroud)
它将等待你的here-document,然后打印hello world.
$ cat > file <<-EOF && echo -n "hello " && echo world
> a
> b
> EOF
hello world
$ cat file
a
b
Run Code Online (Sandbox Code Playgroud)
现在,如果要在heredoc之后放置以下命令,可以将其分组为花括号并继续链接命令,如下所示:
echo -n "hello " && { cat > file <<-EOF
a
b
EOF
} && echo world
Run Code Online (Sandbox Code Playgroud)
$ echo -n "hello " && { cat > file <<-EOF
> a
> b
> EOF
> } && echo world
hello world
$ cat file
a
b
Run Code Online (Sandbox Code Playgroud)
如果你要使用set [-+]e替代的连锁命令有&&,你要注意到,周围的与代码块set -e,并set +e没有直接的替代和解释下你必须要小心:
set [-+]eecho first_command
false # it doesnt stop the execution of the script
# surrounded commands
set -e
echo successful_command_a
false # here stops the execution of the script
echo successful_command_b
set +e
# this command is never reached
echo last_command
Run Code Online (Sandbox Code Playgroud)
如您所见,如果您需要在包围的命令之后继续执行命令,则此解决方案不起作用.
相反,您可以对包围的命令进行分组,以便按如下方式创建子shell:
echo first_command
false # it doesnt stop the execution of the script
# surrounded commands executed in a subshell
(
set -e
echo successful_command_a
false # here stops the execution of the group
echo successful_command_b
set +e # actually, this is not needed here
)
# the script is alive here
false # it doesnt stop the execution of the script
echo last_command
Run Code Online (Sandbox Code Playgroud)
所以,如果你需要你的连锁命令后执行别的东西,你想使用的set内置,考虑上面的例子.
还要注意以下有关子壳的信息:
命令替换,用括号分组的命令和异步命令在子shell环境中调用,该shell环境是shell环境的副本,除了shell捕获的陷阱被重置为shell在调用时从其父级继承的值.作为管道的一部分调用的内置命令也在子shell环境中执行.对子shell环境所做的更改不会影响shell的执行环境.