【问题标题】:BASH Variable scope in subscript下标中的 BASH 变量范围
【发布时间】:2015-06-30 21:51:52
【问题描述】:

我有一个脚本 Onstartup.sh,它循环了 3 个脚本:

#!/bin/bash

#Check services are up and running every 30seconds
while true; do
    . ./script1.sh &
    ./script2.sh &
    ./script3.sh &
    sleep 30
done

script1.sh 给我一个变量正在失去其价值的问题。

#!/bin/bash

echo -e "Variable _X:($_X)"

if [[ $_X -ne 1 ]]; then
    if [ $(somefunction) -ge 1 ]; then
            echo "fix stuff"
        else 
            export _X=1
            echo -e "Variable post script:($_X)"
        fi
    fi
else
    echo "dont fix stuff"
fi

script1.sh 运行并修复内容,然后使其不再运行我设置 _X=1 但是下次循环运行时 _X 再次为空白?

我使用 . (点)脚本,因为这意味着在当前 shell 中运行,所以应该保留 _X 值?

【问题讨论】:

  • 在后台运行脚本会在子shell中运行,因此变量赋值不会影响原始shell。
  • 尝试X=1 &,然后是echo $X,您会发现分配没有任何效果。
  • 谢谢! 100% 后台脚本是新进程。

标签: bash shell variables scope


【解决方案1】:

不要在后台运行script1.sh,因为它在子进程中运行,所以它的变量赋值对原始shell没有任何影响。

while true; do
    . ./script1.sh
    ./script2.sh &
    ./script3.sh &
    sleep 30
done

【讨论】:

    猜你喜欢
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多