在函数Bash中:如何检查参数是否是一个set变量?

4wk*_*wk_ 5 variables bash if-statement

我想实现一个bash函数,test是第一个参数实际上是一个变量,在某处定义.

例如,在我的.bashrc:

customPrompt='yes';
syntaxOn='no';
[...]
function my_func {
    [...]
    # I want to test if the string $1 is the name of a variable defined up above
    # so something like: 
    if [[ $$1 == 'yes' ]];then 
         echo "$1 is set to yes";
    else
         echo "$1 is not set or != to yes";
    fi
    # but of course $$1 doesn't work
}
Run Code Online (Sandbox Code Playgroud)

需要输出:

$ my_func customPrompt
> customPrompt is set to yes
$ my_func syntaxOn
> syntaxOn is set but != to yes
$ my_func foobar
> foobar is not set
Run Code Online (Sandbox Code Playgroud)

我尝试了很多测试,如-v "$1", -z "$1",-n "$1",但他们的测试$ 1作为字符串而不是作为一个变量.(如果我不明白,请纠正我)

jm6*_*666 5

在 中,bash您可以使用间接变量替换。

t1=some
t2=yes
fufu() {
    case "${!1}" in
        yes) echo "$1: set to yes. Value: ${!1}";;
        '')  echo "$1: not set. Value: ${!1:-UNDEF}";;
        *)   echo "$1: set to something other than yes. Value: ${!1}";;
    esac
}

fufu t1
fufu t2
fufu t3
Run Code Online (Sandbox Code Playgroud)

印刷

t1: set to something other than yes. Value: some
t2: set to yes. Value: yes
t3: not set. Value: UNDEF
Run Code Online (Sandbox Code Playgroud)

${!variablename}bash 中的意思是indirect variable expansion. 例如https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html中描述

地点:

参数扩展的基本形式是${parameter}。参数的值被替换。当参数是一个多于一位数字的位置参数时,或者当参数后面跟着一个不被解释为其名称一部分的字符时,需要使用大括号。

如果参数的第一个字符是感叹号 (!),则引入一级变量间接寻址。Bash 使用由参数的其余部分形成的变量的值作为变量的名称;然后扩展该变量,并在其余替换中使用该值,而不是参数本身的值。这称为间接扩展。例外情况是下面描述的 ${!prefix } 和 ${!name[@]} 的扩展。感叹号必须紧跟在左大括号之后才能引入间接关系。

另外,请检查: https: //stackoverflow.com/a/16131829/632407如何在函数中修改间接传递的变量的值。