You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在shell脚本外部获取被调用脚本内的变量值

解决方案
  • 原脚本存在两处核心问题导致无法达到预期:
    1. test1.sh变量赋值语法错误:Shell 中变量赋值时等号两端不能有空格,原脚本的USERVALUES = P1321,testusername@example.com、USERVALUES1 ="$USERVALUES"两行语法不符合规范,直接执行会报错。
    2. 变量作用域问题:直接使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 15:09:02