13

I am having a problem getting my shellscript working using backticks. Here is an example version of the script I am having an issue with:

#!/bin/sh

ECHO_TEXT="Echo this"
ECHO_CMD="echo ${ECHO_TEXT} | awk -F' ' '{print \$1}'"

result=`${ECHO_CMD}`;
echo $result;

result=`echo ${ECHO_TEXT} | awk -F' ' '{print \$1}'`;
echo $result;

The output of this script is:

sh-3.2$ ./test.sh 
Echo this | awk -F' ' '{print $1}'
Echo

Why does the first backtick using a variable for the command not actually execute the full command but only returns the output of the first command along with the second command? I am missing something in order to get the first backtick to execute the command?

benw
  • 887
  • 2
  • 8
  • 20
  • 3
    Backticks are horribly outdated and should not be used any more -- using `$()` instead will save you many headaches – Daenyth Oct 13 '10 at 19:13
  • 4
    Please see [BashFAQ/050](http://mywiki.wooledge.org/BashFAQ/050) (don't put commands in variables) and [BashFAQ/048](http://mywiki.wooledge.org/BashFAQ/048) (avoid using `eval`). Also, your shebang says "#!/bin/sh" and your prompt says "sh", but your question tag says `[bash]` which is not the same thing. – Dennis Williamson Oct 13 '10 at 19:28
  • I didn't set the bash tag, another user changed that after I posted this. – benw Oct 13 '10 at 20:45
  • 1
    POSIX sh supports `$()`. There is no excuse. – Daenyth Oct 13 '10 at 21:18

4 Answers4

16

You need to use eval to get it working

result=`eval ${ECHO_CMD}`;

in place of

result=`${ECHO_CMD}`;

Without eval

${ECHO_TEXT} | awk -F' ' '{print \$1}

which will be expanded to

Echo this | awk -F' ' '{print \$1}

will be treated as argument to echo and will be output verbatim. With eval that line will actually be run.

codaddict
  • 445,704
  • 82
  • 492
  • 529
2

You Hi,

you need to know eval command.

See :

#!/bin/sh

ECHO_TEXT="Echo this"
ECHO_CMD="echo ${ECHO_TEXT} | awk -F' ' '{print \$1}'"

result="`eval ${ECHO_CMD}`"
echo "$result"

result="`echo ${ECHO_TEXT} | awk -F' ' '{print $1}'`"
echo "$result"

Take a look to the doc :

help eval
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
0

In your first example echo is parsing the parameters - the shell never sees them. In the second example it works because the shell is doing the parsing and knows what to do with a pipe. If you change ECHO_CMD to be "bash echo ..." it will work.

verisimilidude
  • 738
  • 3
  • 8
0

Bash is escaping your command for you. Try

ECHO_TEXT="Echo this"
ECHO_CMD='echo ${ECHO_TEXT} | awk -F" " "'"{print \$1}"'"'

result=`${ECHO_CMD}`;
echo $result;

result=`echo ${ECHO_TEXT} | awk -F' ' '{print \$1}'`;
echo $result;

Or even better, try set -x on the first line, so you see what bash is doing

krico
  • 5,723
  • 2
  • 25
  • 28