Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash quoting problem

Tags:

bash

A="echo 'q'"

$A 

I got the result 'q'

but if I type echo 'q' directly, it's q (without single quote)

So, I wonder what rule does bash follow while facing single quotes inside the double quotes.

The original problem is

A="curl http://123.196.125.62/send -H 'Host: poj.org' -e http://poj.org/send"

$A

I got curl: (6) Couldn't resolve host 'poj.org''

it will be all right if I just type the command into the terminal..

P.S. I'd like to use $A for excuting the command inside A

like image 688
Determinant Avatar asked Feb 16 '26 18:02

Determinant


1 Answers

Please see BashFAQ/050: I'm trying to put a command in a variable, but the complex cases always fail!

It's best to avoid putting commands in variables for the reason you've experienced, among others.

You should use a function and pass it arguments.

Why do you want to do this rather than simply executing the command directly?

If you must do it, use an array:

A=(curl http://123.196.125.62/send -H 'Host: poj.org' -e http://poj.org/send)
${A[@]}

Regarding the treatment of single quotes within double quotes, they are treated literally and as part of the rest of the string. Here is the relevant paragraph from man bash:

Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes. The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or <newline>. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed.

like image 176
Dennis Williamson Avatar answered Feb 19 '26 08:02

Dennis Williamson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!