Can someone explain why A and B behave differently?
A=`echo hello how are you | wc -w`
and
CMD="echo hello how are you | wc -w"
B=`$CMD`
They give different results:
$echo $A
4
$echo $B
hello how are you | wc -w
What I would like to have is a command in a variable that I can execute at several points of a script and get different values to compare. It used to work fine but if the command has a pipe, it doesn't work.
CodePudding user response:
``(i.e. backticks) or$()in bash referred as command substitution.""- used e.g. to preserves the literal value of characters, i.e. data.
In the your first example, the command
echo hello how are you | wc -wis executed and its value4assigned toA, hence you get4.In your second example it an assignment of a string to a variable
Band by`$CMD`the|is not "evaluated", and you gethello how are you | wc -w.
What you need can be done with eval command as follows:
CMD="echo hello how are you | wc -w"
echo `eval $CMD` # or just eval $CMD
# Output is 4
