[SOLVED] bash – commands in variables with pipes

Issue

This Content is from Stack Overflow. Question asked by Martin Massera

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.



Solution

  • `` (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" because of late word splitting (see here for further information), 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


This Question was asked in StackOverflow by Martin Massera and Answered by m19v It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?