“cat”命令:如何自动转义所有可能违规的内容?

use*_*685 5 command-line shell quoting cat here-document

如果复制内容

httpd.conf
Run Code Online (Sandbox Code Playgroud)

然后将其粘贴到 cat 命令中.. 比如这个..

#!/bin/bash
cat > /test << EOF
pasted here..
EOF
Run Code Online (Sandbox Code Playgroud)

你遇到这个错误:

-bash: command substitution: line 1: unexpected EOF while looking for matching `''
-bash: command substitution: line 4: syntax error: unexpected end of file
Run Code Online (Sandbox Code Playgroud)

也许解决方案是逃避美元符号,甚至可能是引号等等。

但考虑到这是一个如此大的文件..可以自动转义美元符号吗?

我唯一的选择是通过另一个程序将它们转义,然后将其提供给 cat 命令吗?

Mic*_*mer 6

在“EOF”字符串周围使用引号:

cat > /test <<'EOF'
stuff $(pwd)
EOF
Run Code Online (Sandbox Code Playgroud)

产出

stuff $(pwd)
Run Code Online (Sandbox Code Playgroud)

字面上地。

请参阅heredocs 上的bash 手册。终止符字符串中的任何引号都会阻止正文中的任何扩展和替换。


小智 4

在以下示例中比较此处的两个文档:

(yeti@darkstar:6)~/wrk/tmp$ cat ./xyzzy 
#!/bin/bash
cat << EOF
Version 1 - Today is $(date)
EOF
cat << 'EOF'
Version 2 - Today is $(date)
EOF
(yeti@darkstar:6)~/wrk/tmp$ ./xyzzy 
Version 1 - Today is Sa 21. Jun 08:51:38 CEST 2014
Version 2 - Today is $(date)
Run Code Online (Sandbox Code Playgroud)