bash中值的值

abh*_*air 1 bash shell

我试图编写一个shell脚本来显示作为位置参数传递的环境变量的值.

for i in $@
do
printf "$i" | xargs -I {} echo "${}"
done
Run Code Online (Sandbox Code Playgroud)

但是,上面的代码不起作用.有人可以指导我.

谢谢.

Bar*_*mar 6

您的脚本的问题是xargs不使用shell来执行命令,因此$在参数中不会导致变量扩展.

而是使用间接变量引用,方法是放在!变量名之前,如参数扩展文档中所述.

for i in "$@"
do
    printf "%s = %s\n" "$i" "${!i}"
done
Run Code Online (Sandbox Code Playgroud)

结果:

$ ./testvar.sh HOME USER
HOME = /Users/barmar
USER = barmar
Run Code Online (Sandbox Code Playgroud)