My current shell is bash, but
echo '1 2 3 4'| awk '{print $2}'
and
bash -c " echo '1 2 3 4'| awk '{print $2}' "
gives different result. Os is Linux. What's wrong on second statement?
My current shell is bash, but
echo '1 2 3 4'| awk '{print $2}'
and
bash -c " echo '1 2 3 4'| awk '{print $2}' "
gives different result. Os is Linux. What's wrong on second statement?
How about using a HERE-document?
bash <<'EOH'
echo '1 2 3 4'| awk '{print $2}'
EOH
Note that I have dropped the -c option to bash, and that the single quotes around EOH are necessary to avoid evaluating $2 on the shell level.
In your second command, $2
is evaluated before being handed to awk
, which gives the following command :
echo "1 2 3 4" | awk "{print }"
To avoid this, you can use this awful syntax :
bash -c 'echo "1 2 3 4"| awk '"'"'{print $2}'"'"''
Or this syntax suggested by chepner :
bash -c $'echo "1 2 3 4" | awk \'{print $2}\''
The problem is that variable expansion is done twice here : a first time when the bash -c
command is evaluated, and a second time when the spawned bash
process evaluates its command line.
My initial answer was to change the command to bash -c 'echo "1 2 3 4"| awk "{ print $2 }'"
, which indeed avoided expansion in your current shell. However, in the spawned bash
process, expansion was executed on the following command :
echo "1 2 3 4" | awk "{print $2 }"
And $2
was expanded to the empty string.
So we need this command to be executed by the spawned bash
:
echo "1 2 3 4" | awk '{print $2 }'
And we need to surround it with single quotes in the current shell :
bash -c 'echo "1 2 3 4" | awk '{print $2 }''
Except here the awk
quotes close the bash -c
parameter's quotes, which leads to the above command where we use '"'"'
to write a single quote inside a singe-quoted text.