防止 bash 在不引用所有内容的情况下进行解释

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9869902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:51:40  来源:igfitidea点击:

Prevent bash from interpreting without quoting everything

bash

提问by lzap

I need to output some text as bash script, but in a script. I use cat for this, but it has one drawback. It interprets variables and stuffduring it is being written. I do want to prevent this.

我需要输出一些文本作为 bash 脚本,但在脚本中。我为此使用 cat,但它有一个缺点。它在写入过程中解释变量和内容。我确实想防止这种情况

How to do that without quoting all varibles(my script is failrly long)? Example

如何在不引用所有变量的情况下做到这一点(我的脚本很长)?例子

cat >/tmp/script << EOF
  $HOSTNAME
  # lots of other stuff I do NOT want to escape like $VARIABLE
  # ...
EOF

cat /tmp/script
myhostname.mylan

I want:

我想要:

cat /tmp/script
$HOSTNAME

Edit: Please note my script (here only $HOSTNAME) is very long, I dont want to change it all. Also single quoting does not workwith <<

编辑:请注意我的脚本(这里只有$HOSTNAME)很长,我不想改变它。同时单引号不起作用与<<

cat >/tmp/script '<< EOF
  $HOSTNAME
EOF'
File not found: EOF'

What's the trick? Thanks.

有什么诀窍?谢谢。

回答by torek

If you want everything quoted:

如果你想引用所有内容:

cat << 'EOF'
stuff here with $signs is OK
as are `backquotes`
EOF

See the section on "here documents" in the manual.

请参阅手册中有关“此处文档”的部分。

回答by Eran Ben-Natan

Escape the $:

转义 $:

cat >/tmp/script << EOF
  $HOSTNAME
EOF

回答by user unknown

Use sed:

使用 sed:

 sed -n '20,30p' "
#!/bin/bash
cat >/dev/null << EOF
 3
 4 $HOSTNAME
 5 ls 
 6 $(ls -l) 
 7
 8 echo 'foo
 9 bar' 
 10
 11 echo "Foo
 12 $((4+4)) Bar" 
EOF
sed -n '3,12p' "
echo '
$HOSTNAME
...
' >> /tmp/script
" echo "fine?"
"

to print line 20 to 30, SSCE:

打印第 20 到 30 行,SSCE:

##代码##

working with head/tail should work too.

使用头/尾也应该工作。

You will have to adjust the numbers, if you work on it and insert or delete lines.

如果您处理并插入或删除行,您将不得不调整数字。

回答by WilQu

Try with echo :

尝试使用 echo :

##代码##