Problem with backticks in shellscript

怎甘沉沦 提交于 2019-12-01 03:38:05

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.

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

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.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!