如何在shell脚本外部获取被调用脚本内的变量值
解决方案
- 原脚本存在两处核心问题导致无法达到预期:
test1.sh变量赋值语法错误:Shell 中变量赋值时等号两端不能有空格,原脚本的USERVALUES = P1321,testusername@example.com、USERVALUES1 ="$USERVALUES"两行语法不符合规范,直接执行会报错。- 变量作用域问题:直接使用
sh执行test1.sh时,test1.sh会运行在独立子进程中,子进程内定义的变量无法传递给运行test2.sh的父Shell进程,因此test2.sh最终echo语句无法读取到USERVALUES1的值。
具体修改方法
1. 修正/opt/shellscript/test1.sh内容
USERVALUES=P1321,testusername@example.com USERVALUES1="$USERVALUES" echo "Value of USERVALUES1 is $USERVALUES1"
2. 修正/opt/shellscript/test2.sh内容
将sh执行改为source(或简写为.)执行,让test1.sh的代码直接在test2.sh的当前Shell上下文运行,变量会被保留:
chmod +x /opt/shellscript/test1.sh source /opt/shellscript/test1.sh # 也可替换为 . /opt/shellscript/test1.sh 效果完全相同 echo "Value of USERVALUES1 from script test1.sh is $USERVALUES1"
验证效果
执行sh /opt/shellscript/test2.sh即可得到预期输出:
Value of USERVALUES1 from script test1.sh is P1321,testusername@example.com
内容的提问来源于stack exchange,提问作者praseeb kdas
相关产品推荐
相关产品推荐

