C/C++教程

Shell 脚本避免多次重复 source

本文主要是介绍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_

 

这篇关于Shell 脚本避免多次重复 source的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!