bashpipecommand-substitution

bash - commands in variables with pipes


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

    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, the 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