shell脚本之变量嵌套


0,根据以往的经验,变量嵌套应该是${${var}}这种方式,那我们来试一下.

1
2
3
4
5
6
7
8
[[email protected] shell]# var='test'
[[email protected] shell]# test='abcd'
[[email protected] shell]# echo ${var}
test
[[email protected] shell]# echo ${${var}}
-bash: ${${var}}: bad substitution
[[email protected] shell]# echo $(echo '$'${var})
$test

可以看到这种方式是失败的,哎我艹,最后一条命令都这样了你都不出来变量的值?还好系统为我们准备了获取嵌套变量的命令…

1
2
[[email protected] shell]# eval echo $(echo '$'${var})
abcd

很简单,就是在你变量前面加上一个’$’符,然后使用eval命令就可以获取它的值了!
但是这有什么用呢?我直接通过函数或者case来写就行了,下面做个简单的演示.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
userName=${1}
aaa() {
echo select test from psql where user=${userName} and id=1;
}
bbb() {
echo select test from psql where user=${userName} and id=2;
}
ccc() {
echo select test from psql where user=${userName} and id=3;
}
$1
[[email protected] shell]# ./test.sh aaa
select test from psql where user=aaa and id=1
[[email protected] shell]# ./test.sh bbb
select test from psql where user=bbb and id=2
[[email protected] shell]# ./test.sh ccc
select test from psql where user=ccc and id=3

通过函数的方式可以手动指定其余条件的值,但是如果有大量的内容,使用函数就显得太过于复杂了,下面通过嵌套变量再来看一下

1
2
3
4
5
6
7
8
9
10
11
userName=${1}
aaa=1
bbb=2
ccc=3
echo select test from psql where user=${userName} and id=$(eval echo '$'"$1");
[[email protected] shell]# ./test.sh aaa
select test from psql where user=aaa and id=1
[[email protected] shell]# ./test.sh bbb
select test from psql where user=bbb and id=2
[[email protected] shell]# ./test.sh ccc
select test from psql where user=ccc and id=3

先提前定义好需要嵌套变量的值,然后下面直接调用就行了,简单粗暴省事!