linux - 在 bash 中传递给函数的变量名

标签 linux bash

bash 中有没有办法理解传递给它的变量的名称?

例子:

var1=file1.txt
err_var=errorfile.txt

function func1 {
   echo "func1: name of the variable is: " $1
   echo "func1: value of variable is: " $1 
   echo
   if [ ! -e $var1 ]
   then
      $1 = $err_val  #is this even possible?
   fi
   func2 $1
}

function func2 {
   echo "func2: name of the variable is: " $1
   echo "func2: value of variable is: " $1 
   echo
}

func1 $var1
func1 $err_var

如果 file1.txt 存在,我希望得到以下输出:

func1: name of the variable is: var1
func1: value of variable is: file1.txt

func2: name of the variable is: var1
func2: value of variable is: file1.txt

当 file1.txt 不存在时:

func1: name of the variable is: var1
func1: value of variable is: file1.txt

func2: name of the variable is: err_var
func2: value of variable is: errorfile.txt

有什么想法吗?

最佳答案

不,变量在函数看到它之前就被展开了。该函数只看到值,而不是变量名。

如果传递的变量名未展开且没有美元符号,则可以使用间接寻址。

get_it () {
    echo "${!1}"
}

演示:

$ foo=bar
$ baz=qux
$ get_it foo
bar
$ get_it baz
qux

关于linux - 在 bash 中传递给函数的变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10955479/

相关文章:

python - 如何在 PythonAnywhere 上将变量打印到 Bash 控制台?

linux - 是否可以在远程 shell 脚本中调用函数?

linux - Makefile 没有按预期执行命令

linux - 尝试放置错误变量时如何修复 Tcl 'Command not found' 错误?

bash - 如何在 FFMPEG 的同一命令中使用 -vf 和 -filter_complex

bash - 如何将变量设置为 Bash 中命令的输出?

linux - Ubuntu 14.04 - 内核无法使用 make-kpkg 编译

linux - 从第二个元素开始循环 - Shell 脚本

linux - 内核栈和用户空间栈

linux - 如何忽略 shell 终端中的响应?