Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with backticks in shellscript

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?

like image 383
benw Avatar asked Oct 13 '10 19:10

benw


2 Answers

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.

like image 184
codaddict Avatar answered Sep 27 '22 21:09

codaddict


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
like image 30
Gilles Quenot Avatar answered Sep 27 '22 20:09

Gilles Quenot