Here Document 小技巧

我们经常在 Linux 中使用 Here Document 来快速的写入多行文本内容到文件之中,但是不知道大家有没有注意到在 Here Document 中如果我们使用了 \, $`, 我们写入的结果往往会与我们的预期有很大的不同。

例如,如果我们使用一下命令进行插入文本到 test.txt 文件中

# cat<<EOF>> test
> Hello, world!
> Hello, $(whoami)!
> EOF

我们原本不希望 $(whoami) 被展开,可实际上,我们得到的却是展开后的结果:

# cat test
Hello, world!
Hello, Kaol!

那么我们怎么才能禁止 Here Document 将这些特殊字符展开呢?其实在 Bash 手册中就有明确的说明:

If any part of word is quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded.

所以我们只需要在执行命令的时候将 EOF 这个单词中任意一个部分用引号包裹起来,Here Document 中的特殊字符就将不会被扩展。例如, cat <<"EOF">> testcat <<"E"OF>> test 或者 cat <<"EO"F>> test 这样都是可以的。

# cat<<"EOF">> test
> Hello, world!
> Hello, $(whoami)!
> EOF
# cat test
Hello, world!
Hello, $(whoami)!

Bash 手册中还有提到另一个小技巧,那就是如果我们使用的是 <<- 作为重定向操作符,而不是 << 的话,那么 Here Document 就会把每一行的行首的制表符给忽略掉。

# cat<<EOF>> test
>       Hello, world!
>   Hello, $(whoami)!
> EOF
# cat test
Hello, world!
Hello, Kaol!
版权声明:
作者:Kaol
链接:https://www.kaol.net/linux/here-document-tips.html
来源:Kaol's Blog
本站文章除特殊标明者外均为原创,版权所有,未经允许严禁转载!
THE END
分享
二维码
< <上一篇
下一篇>>
文章目录
关闭
目 录