Home > front end >  bash - commands in variables with pipes
bash - commands in variables with pipes

Time:09-19

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.
  1. In the your first example, the command echo hello how are you | wc -w is executed and its value 4 assigned to A, hence you get 4.

  2. In your second example it an assignment of a string to a variable B and by `$CMD` the | is not "evaluated", and you get hello 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
  • Related