Bash 脚本问题
我可以很好地运行这个命令,并得到我想要的输出:
ifconfig eth0 | grep HWaddr | awk '{print $5}'
但是,当我将命令设置为变量并打印该变量时,我收到错误:
CASS_INTERNAL=`ifconfig eth0 | grep HWaddr | awk '{print \$5}'`
$CASS_INTERNAL
not find
my inside xxx ip: command 奇怪的事情 - 我的内部 IP 实际上出现了。我该如何处理而不出现错误?没关系,但我使用的是最新版本的 Ubuntu。
I can run this command fine, with the output I want:
ifconfig eth0 | grep HWaddr | awk '{print $5}'
However, when I set the command to a variable, and print the variable, I get an error:
CASS_INTERNAL=`ifconfig eth0 | grep HWaddr | awk '{print \$5}'`
$CASS_INTERNAL
my internal xxx ip: command not found
The weird thing - my internal IP actually shows up. How do I go about this without getting an error? It shouldn't matter, but I'm using the latest version of Ubuntu.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您没有打印变量,而是将其作为命令名称运行。您正在寻找
(养成总是在变量替换周围加上双引号的习惯。)
更高级的 shell 注意:在这种情况下,这并不重要,但一般来说
echo
可能会遇到一些问题特殊字符(-
和\\
),因此最好使用以下更复杂但完全可靠的命令:You're not printing the variable, you're running it as a command name. You're looking for
(Get into the habit of always putting double quotes around variable substitutions.)
More advanced shell note: in this case it doesn't matter, but in general
echo
can have trouble with some special characters (-
and\\
), so it's better to use the following more complicated but fully reliable command:不必使用
grep
don't have to use
grep
您的:
会尝试将其作为命令运行。
Your:
Would try to run it as a command.
你也许想要吗
do you maybe want
好吧,您首先 grep 查找 HWaddr,因此这一行的第五个字段是相关网络适配器的 MAC 地址,而不是您的本地 IP 地址。
其他人建议解决方案是简单地回显结果,这意味着如果本示例中的 eth0 在执行该行的时间点不可用,则它将无法工作。
据我了解,您希望将所需的命令行放入变量中,然后稍后对其进行评估。这种模式通常称为延迟评估,并且可以在 bash 中实现 通过使用 eval 内置函数:
Well, you grep for HWaddr first, so the fifth field on this this line is the MAC address of the network adapter in question - not your local IP address.
Others have suggested the solution is to simply echo the result, meaning if eth0 in this example is not available at that point in time which the line gets executed, it will not work.
From what I understand you wish instead to put the desired command line in a variable, then evaluate it later on. This pattern is commonly called lazy evaluation, and is made possible in bash by using the eval builtin: