viz
viz

Reputation: 1277

Difference between "&&" inside variable and outside variable in shell script

Just out of curiosity:

A="echo hi"
B="echo hello"
C="$A && $B"

echo $C // prints "echo hi && echo hello"
$C
echo "$A && $B" // prints "echo hi && echo hello"
$A && $B

I though this would work in a same manner. But it shows different results as this:

echo hi && echo hello
hi && echo hello
echo hi && echo hello
hi
hello

Why?

Upvotes: 3

Views: 1052

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295472

Very Short Answer

Read BashFAQ #50.

Slightly Short Answer

Variable expansions do not go through all parsing steps (indeed, if they did, it would be impossible to write scripts securely processing untrusted data in bash). Unquoted expansions go through string-splitting and glob expansion only -- these stages split strings into pieces, and evaluate those pieces as globs, but don't recognize any of those pieces as syntax. Quoted expansions are substituted literally, meaning they stay strings, period.

Thus:

echo $C         # runs: "echo" "echo " "hi" "&&" "echo" "hello"
$C              # runs: "echo " "hi" "&&" "echo" "hello"
echo "$A && $B" # runs: "echo" "echo hi && echo hello"
$A && $B        # runs: "echo" "hi" && "echo" "hello"

Notice how in the last example, the && wasn't quoted? That represents that it was parsed as syntax, not data. As syntax, && acts as a command separator (whereas as data, it just gets passed to echo).

Upvotes: 7

Related Questions