访问和更新其他脚本中的shell脚本变量
问题描述:
我有一个shell脚本parent.sh像这样。我希望变量标志在child.sh使用,更新标志的价值那里得到更新值回parent.sh。我怎样才能做到这一点。访问和更新其他脚本中的shell脚本变量
#!/bin/bash
flag=999 #I want ths flag in child.sh and there i will update its value depending on some condition
$HOME/child.sh
if [ $? -eq $flag ];then #The value of flag got changed on child.sh
echo "Success"
else
echo "Failed"
fi
而且我child.sh如下
#!/bin/bash
hive -f $HOME/creat.hql #It should be create.hql so it will fail.
if [ $? -eq 0 ];then
flag=0
else
flag=1 #This will execute and I want this change to be get reflected in parent.sh
fi
答
您需要source
child.sh
在parent.sh
以便它在当前子shell执行:
#!/bin/bash
flag=999 #I want ths flag in child.sh and there i will update its value depending on some condition
. ./child.sh
if [ $? -eq $flag ];then #The value of flag got changed on child.sh
echo "Success"
else
echo "Failed"
fi
你可以检查flag
正确的价值在采购child.sh
后确保其正确设置在child.sh
之内。有关source
如何工作的更多信息,请参见或help .
里面的bash
。
+0
_source_使_child.sh_中的所有命令执行,我不想要。我只想访问和使用_flag_变量 – MrG
+0
我认为你不能这样做。每个脚本都是在一个单独的bash过程中执行的,孩子无法修改其父代的环境。 –
你为什么要使用child.sh的返回值以及更改的标志变量?你可以简单地把'exit $ flag'放在child.sh的末尾,然后使用'if [$ flag -eq 0];然后回声“成功”'... –
我如何能在_child.sh_ – MrG
使用'标志= $访问的变量_flag_?'电话后,直接让你有返回值(你用'$退出在flag'设置剧本)。您不使用脚本中的标志值,但您具有相同的值(假设值只能是0-127)。我的意思是说'如果[$? -eq 0];然后......在我上面的评论中回显“成功”,但将退出值赋值给一个变量更安全,如果你希望那也可以称为'flag' –