我想知道什么时候使用 cat <<
比简单地使用 <<
更可取.我正在 ZSH shell 中进行测试,并且
cat <<EOF
Hello world!
EOF
输出相同的
<<EOF
Hello world!
EOF
.
var=$(cat <<EOF
Hello world!
EOF
)
具有相同的变量值
var=$(<<EOF
Hello world!
EOF
)
两种形式的 here-doc 之间的实际区别是什么?
最佳答案
只要 zsh 默认行为(例如调用 zsh -f
),两个示例之间就没有区别。我们可以通过 zsh -x -f
调用这两个示例来检查跟踪输出。 , cat
即使在后一种情况下也会被实际调用。
尽管这些差异在 Redirections with no command, zshmisc(1)
中有所描述. zsh 将在没有命令的情况下以多种方式进行重定向,因此我们可以对其进行处理以免破坏任何内容:
cat
明确地。 Redirections with no command
When a simple command consists of one or more redirection operators and zero or more parameter assignments, but no command name, zsh can behave in several ways.
If the parameter NULLCMD is not set or the option CSH_NULLCMD is set, an error is caused. This is the csh behavior and CSH_NULLCMD is set by default when emulating csh.
If the option SH_NULLCMD is set, the builtin ‘:’ is inserted as a command with the given redirections. This is the default when emulating sh or ksh.
Otherwise, if the parameter NULLCMD is set, its value will be used as a command with the given redirections. If both NULLCMD and READNULLCMD are set, then the value of the latter will be used instead of that of the former when the redirection is an input. The default for NULLCMD is ‘cat’ and for READNULLCMD is ‘more’.Thus
< file
shows the contents of file on standard output, with paging if that is a terminal. NULLCMD and READNULLCMD may refer to shell functions.
因此,在后一种情况下,
$var
如果 zsh shell 选项 SH_NULLCMD
将不会被设置设置等。# I've tested with running `zsh -f` to check the various behaviors.
test-nullcmd () {
local var=$(<<EOF
Hello world!
EOF
)
echo "$var"
}
test-nullcmd
#> Hello world!
() {
setopt localoptions shnullcmd
test-nullcmd
}
# nothing will be printed
() {
setopt localoptions cshnullcmd
test-nullcmd
}
# test-nullcmd:1: redirection with no command (error)
() {
local NULLCMD=
test-nullcmd
}
# test-nullcmd:1: redirection with no command (error)
顺便说一句,我们可以使用
command cat
而不是 cat
只是为了防止别名扩展。
关于zsh - 为什么不使用 <<EOF 而不是 cat <<EOF ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37233240/