zsh - 为什么不使用 <<EOF 而不是 cat <<EOF ?

标签 zsh cat io-redirection

我想知道什么时候使用 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.

    -- Redirections with no command, zshmisc(1)



    因此,在后一种情况下,$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/

    相关文章:

    performance - ZSH 的时间命令是否接受任何参数,如 -p?

    bash - 具有平均背景颜色的壁纸的 Shell 脚本

    c++ - native C/C++ 中衍生进程的标准输入和输出的跨平台重定向(使用解决方案编辑)

    zsh - 为什么我的历史记录没有保存在 zsh 选项卡之间?

    linux - 从 .txt 文件中删除扩展 ASCII 字符 Linux 终端

    regex - 提取包含一个或多个数字的文件名,然后将 cat 内容提取到输出文件

    unix - 连接多个文件,但包含文件名作为节标题

    python - 更改运行进程的输出重定向

    c - fprintf 不在 ^C 上写入,但在退出时写入

    bundler - 如何防止bundler生成binstubs?