问题描述
我在使用反引号使我的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;
此脚本的输出为:
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?
推荐答案
您需要使用 eval
使其正常工作
You need to use eval
to get it working
result=`eval ${ECHO_CMD}`;
代替
result=`${ECHO_CMD}`;
没有 eval
${ECHO_TEXT} | awk -F' ' '{print \$1}
这将扩展为
Echo this | awk -F' ' '{print \$1}
将被视为<$ c的参数$ c> echo 并逐字输出。在 eval
中,该行实际上将运行。
will be treated as argument to echo
and will be output verbatim. With eval
that line will actually be run.
这篇关于Shellscript中的反引号问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!