Shell 脚本避免多次重复 source


https://kodango.com/avoid-repeated-source-in-shell

${!_sourced_}是间接引用,这个执行没问题,source 会报错 bad substitution 

_sourced_="__sourced_$$__"

echo "Flag variable $_sourced_=${!_sourced_}"

if [ -z "${!_sourced_}" ]; then
    eval "$_sourced_=1"
    echo "It is the first time to source script"
else
    echo "The script have been sourced"
fi

改为下面就可以正常source

_sourced_="__sourced_$$__"

sourced=`eval echo '$'"$_sourced_"`

echo "Flag variable $_sourced_=${sourced}"

if [ -z "${sourced}" ]; then
    eval "$_sourced_=1"
    echo "It is the first time to source script"
else
    echo "The script have been sourced"
fi

或者

_sourced_="__sourced_$$__"

eval sourced=\$$_sourced_

echo "Flag variable $_sourced_=${sourced}"

if [ -z "${sourced}" ]; then
    eval "$_sourced_=1"
    echo "It is the first time to source script"
else
    echo "The script have been sourced"
fi

_sourced_="__sourced_$$__"
echo $_sourced_

https://stackoverflow.com/questions/2683279/how-to-detect-if-a-script-is-being-sourced

相关