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/