【发布时间】:2015-04-18 21:51:18
【问题描述】:
我在 Shell Scripting 中遇到了一件有趣的事情,但不是 100% 确定为什么会出现这样的行为
我尝试了以下脚本:
#!/bin/sh
CMD="curl -XGET http://../endpoint";
var1=eval $CMD | sed -e 's/find/replace/g';
echo $var1; # Output: printed the value on this line
echo $var1; # Output: blank/no data printed (Why it is blank?)
我必须更改用反引号 ` 括起来的变量中的命令,以便根据需要多次打印变量。
CMD="curl -XGET http://../endpoint";
var1=`eval $CMD | sed -e 's/find/replace/g'`;
echo $var1; # Output: printed the value on this line
echo $var1; # Output: printed the value on this line
- 为什么我必须用 ` 包围我的命令,以便在后续变量使用中将它的 o/p 分配给变量?
我感觉它与变量命令范围有关。
我们将不胜感激!
更新: 我尝试了以下命令,它在我的环境中工作。
#!/bin/sh
CMD="curl -XGET http://www.google.com/";
var1=eval $CMD | sed -e 's/find/replace/g';
echo $var1; # Output: printed the value on this line
echo "######";
echo $var1; # Output: blank/no data printed (Why it is blank?)
【问题讨论】:
-
请注意,'$(...)' 语法优于反引号语法。这是一个解释:mywiki.wooledge.org/BashFAQ/082
-
感谢 pmohandas 的建议。
标签: bash shell variables scope command