在双引号内执行本地 bash 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10887519/
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
Execute a local bash variable inside double quotes
提问by jdorfman
Hypothetically I have four webservers that I need to add a line of HTML to a file. As you can see I need the integer to appear after cluster=
假设我有四个网络服务器,我需要向文件添加一行 HTML。如您所见,我需要在cluster=之后出现整数
for i in 01 02 03 04; do ssh web.${i}.domain.com 'echo "<img src=beacon.gif?cluster=${i}>" >> /var/www/index.html'; done
How can this be accomplished? Thanks in advance.
如何做到这一点?提前致谢。
回答by nosid
Please note the 'before and after ${i}:
请注意'之前和之后${i}:
for i in 01 02 03 04; do
ssh web.${i}.domain.com 'echo "<img src=beacon.gif?cluster='${i}'>" >> /var/www/index.html'
done
Edit:There is a huge difference between quoting in shell and string literals in programming languages. In shell, "quoting is used to remove the special meaning of certain characters or words to the shell" (bash manual). The following to lines are identical to bash:
编辑:shell 中的引用和编程语言中的字符串文字之间存在巨大差异。在 shell 中,“引用用于去除某些字符或单词对 shell 的特殊含义”(bash 手册)。以下 to 行与 bash 相同:
'foo bar'
foo' 'bar
There is no need to quote the alphabetic characters - but it enhances the readability. In your case, only special characters like "and <must be quoted. But the variable $icontains only digits, and this substitution can be safely done outside of quotes.
不需要引用字母字符 - 但它增强了可读性。在您的情况下,只有像"和 之类的特殊字符<必须被引用。但是变量$i只包含数字,并且可以在引号之外安全地进行这种替换。
回答by Alex Howansky
I think this should do it:
我认为应该这样做:
"echo \"<img src=beacon.gif?cluster=${i}>\" >> /var/www/index.html"
回答by twalberg
for i in 01 02 03 04
do
ssh web.${i}.domain.com "echo \"<img src=beacon.gif?cluster=${i}>\" >> /var/www/index.html
done
Basically, just use double quotes, but you'll have to escape the inner ones.
基本上,只需使用双引号,但您必须转义内部的引号。

