【问题标题】:bash variable not available after running script [duplicate]运行脚本后bash变量不可用[重复]
【发布时间】:2017-09-17 14:58:13
【问题描述】:
我有一个将我的 IP 地址分配给变量的 shell 脚本,但是在运行脚本后,我无法在 bash 中访问该变量。如果我在脚本中添加回显,它将打印变量,但在脚本运行完成后不会保存它。
有没有办法在脚本运行后更改脚本以访问它?
ip=$(/sbin/ifconfig | grep "inet " | awk '{print $2}' | grep -v 127 | cut -d":" -f2)
我在 Mac 上使用终端。
【问题讨论】:
标签:
bash
variables
terminal
【解决方案1】:
默认情况下,脚本在子进程中运行,这意味着当前(调用)shell 看不到它的变量。
您有以下选择:
-
使脚本输出信息(到标准输出),以便调用shell可以捕获它并将它分配给它自己的变量。这可能是最干净的解决方案。
ip=$(my-script)
-
Source 脚本,使其在 current shell 而非子进程中运行。但是请注意,您在脚本中对 shell 环境所做的所有修改都会影响当前的 shell。
. my-script # any variables defined (without `local`) are now visible
-
将您的脚本重构为您在当前shell中定义的函数(例如,将其放在~/.bashrc中);同样,该函数所做的所有修改都将对当前 shell 可见:
# Define the function
my-func() { ip=$(/sbin/ifconfig | grep "inet " | awk '{print $2}' | grep -v 127 | cut -d":" -f2); }
# Call it; $ip is implicitly defined when you do.
my-func
顺便说一句:您可以将命令简化如下:
/sbin/ifconfig | awk '/inet / && $2 !~ /^127/ { print $2 }'