在一行中链接命令
您可以将control operator && 紧跟在here document 中的EOF 单词之后,并且可以链接多个命令:
cat > file <<-EOF && echo -n "hello " && echo world
它将等待您的 here-document,然后打印 hello world。
示例
$ cat > file <<-EOF && echo -n "hello " && echo world
> a
> b
> EOF
hello world
$ cat file
a
b
现在,如果您想在heredoc 之后放置以下命令,您可以将group 放在花括号中并继续链接 命令,如下所示:
echo -n "hello " && { cat > file <<-EOF
a
b
EOF
} && echo world
示例
$ echo -n "hello " && { cat > file <<-EOF
> a
> b
> EOF
> } && echo world
hello world
$ cat file
a
b
如果您要使用set [-+]e 而不是链式命令 与&&,您必须注意用set -e 和set +e 包围一段代码不是直接替代方案,您必须注意以下事项:
echo first_command
false # it doesn't 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
如您所见,如果您需要在包围命令之后继续执行命令,此解决方案不起作用。
相反,您可以对被包围的命令进行分组,以创建一个子shell,如下所示:
echo first_command
false # it doesn't 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 doesn't stop the execution of the script
echo last_command
因此,如果您需要在您的链式命令之后执行其他操作并且您想使用the set builtin,请考虑上面的示例。
还要注意以下关于subshells:
命令替换、用括号分组的命令和异步命令在作为 shell 环境副本的子 shell 环境中调用,除了 shell 捕获的陷阱被重置为 shell 在调用时从其父 shell 继承的值.作为管道的一部分调用的内置命令也在子 shell 环境中执行。对子 shell 环境所做的更改不会影响 shell 的执行环境。