用eval,可以把字符串当作命令来执行:
val=2
eval "x=\$$val"
echo $x
val=1
x=( "$@" )
echo "${x[$val]}"
注意:数组是从0开始的,也就是 ${x[0]} 对应 $1、${x[1]} 对应 $2,依次类推……
一个@称为用户定义变量 两个@@称为系统定义变量。User variables are written as @var_name, User-defined variables are session specific. A user variable defined by one client cannot be seen or used by other clients.
如果是bash,可以用indirect expansion来搞,语法为 ${!var}。比如
foo=bar
bar=123
echo ${!foo}
会打印 123
再比如下面的脚本,依次打印脚本的各个输入参数。
#!/bin/bash
var=1
while [ $var -le $# ]
do
echo "Param $var is ${!var}"
let var++
done
不用indirect expansion,也可以用 eval, 比如
#!/bin/bash
var=1
while [ $var -le $# ]
do
eval echo "Param $var is \$$var"
let var++
done
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)