Bash - Here Documents & Strings

Here Documents

这是一种重定向, 可以让 shell 读取输入直至碰到某个词, 读取的内容会作为 standard input.

语法:

[n]<<[-]word
here-document
delimiter

示例:

➜  cat <<EOF
heredoc> hi
heredoc> i
heredoc> am
heredoc> niko
heredoc> EOF
hi
i
am
niko

如上, EOF 之间的就是 Here Documents, 它会被重定向给 cat 命令.

其中 << 可以换成 <<-, 这时每一行前面的 tab 字符将会被移除, 这是为了让 shell 脚本编写时缩进更自然, 如下:

➜  cat <<-EOF
heredocd> hi
heredocd> i
heredocd> EOF
hi
i


➜ cat <<EOF
heredoc> hi
heredoc> i
heredoc> EOF
hi
i

Here Strings

它是 Here Documents 的变种, 可以输入字符串 :

[n]<<< word

有什么用

因为 bash 里如果用到 pipe, 那意味着命令会在 subshell 里运行, 比如 :

$ echo "hello world" | read first second
$ echo $second $first

打印结果将会是空的.

使用 Here Strings 则可以读取变量 :

$ read first second <<< "hello world"
$ echo $second $first
world hello

参考

https://unix.stackexchange.com/questions/80362/what-does-mean