Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a local bash variable inside double quotes

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=

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.

like image 478
jdorfman Avatar asked Jun 04 '12 19:06

jdorfman


People also ask

How do you use a variable inside a double quote?

Use a formatted string literal to add double quotes around a variable in Python, e.g. result = f'"{my_var}"' . Formatted string literals let us include variables inside of a string by prefixing the string with f .

How do you pass a variable in double quotes in Linux?

Variable substitutions should only be used inside double quotes. Outside of double quotes, $var takes the value of var , splits it into whitespace-delimited parts, and interprets each part as a glob (wildcard) pattern. Unless you want this behavior, always put $var inside double quotes: "$var" .

How do you pass a double quote in bash?

Single quotes(') and backslash(\) are used to escape double quotes in bash shell script. We all know that inside single quotes, all special characters are ignored by the shell, so you can use double quotes inside it. You can also use a backslash to escape double quotes.

How do you echo the variable inside a single quote?

`echo` command prints the value of this variable without any quotation. When the variable is quoted by single quote then the variable name will print as output. If the backslash ( \ ) is used before the single quote then the value of the variable will be printed with single quote.


2 Answers

Please note the ' before and after ${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:

'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 $i contains only digits, and this substitution can be safely done outside of quotes.

like image 71
nosid Avatar answered Nov 19 '22 23:11

nosid


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.

like image 28
twalberg Avatar answered Nov 20 '22 01:11

twalberg