5

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.

1

1 Answer 1

5
  • `` (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, 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
Sign up to request clarification or add additional context in comments.

5 Comments

an assignment of a string to a variable B and by $CMD its value is not "evaluated" --> if that were the case, then B would equal "echo hello how are you | wc -w" but it doesn't: it equals "hello how are you | wc -w". So the echo command was executed. It just didn't pipe into wc.
@k314159 adjusted my answer.
I still don't understand what is the logic behind running the echo but not the pipe... But thanks for giving the eval solution!
@MartinMassera Because of 'late word splitting' the pipe it not evaluated, see unix.stackexchange.com/a/388352/393118 for further information. I add the link to my answer as well.
It's important to use quotes -- eval "$CMD", not eval $CMD. Otherwise you can get filenames injected into code if your string word-splits to include any globs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.