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

我想实现一个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
}

需要输出:

$my_func customPrompt
> customPrompt is set to yes
$my_func syntaxOn
> syntaxOn is set but != to yes
$my_func foobar
> foobar is not set

我尝试了很多测试,比如-v“$1”,-z“$1”, – n“$1”,但是所有这些都测试$1作为字符串而不是变量.
(如果我不明白,请纠正我)

最佳答案
在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

版画

t1: set to something other than yes. Value: some
t2: set to yes. Value: yes
t3: not set. Value: UNDEF

bash中的${!variablename}意味着间接变量扩展.在例如https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html

Whrere:

The basic form of parameter expansion is ${parameter}. The value of
parameter is substituted. The braces are required when parameter is a
positional parameter with more than one digit, or when parameter is
followed by a character that is not to be interpreted as part of its
name.

If the first character of parameter is an exclamation point (!), a
level of variable indirection is introduced. Bash uses the value of
the variable formed from the rest of parameter as the name of the
variable; this variable is then expanded and that value is used in the
rest of the substitution, rather than the value of parameter itself.
This is known as indirect expansion. The exceptions to this are the
expansions of ${!prefix } and ${!name[@]} described below. The
exclamation point must immediately follow the left brace in order to
introduce indirection.

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

转载注明原文:在函数Bash中:如何检查参数是否是一个set变量? - 代码日志