BASH下标中的变量范围

时间:2015-06-30 21:51:52

标签: bash shell variables scope

我有一个脚本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值?

1 个答案:

答案 0 :(得分:2)

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

while true; do
    . ./script1.sh
    ./script2.sh &
    ./script3.sh &
    sleep 30
done
相关问题