在函数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:
另外,检查一下:https://stackoverflow.com/a/16131829/632407如何在函数中修改间接传递的变量的值. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |