获取名称由变量本身组成的变量的值
Get the value of a variable whose name consists of a variable itself
脚本:
#!/bin/bash
for SID in db1 db2 db3 db4
do
"$SID"_fs=$(
df -k
| grep "$SID\/data"
| tr -s ' '
| cut -d' ' -f6
| awk '{print substr([=10=],length([=10=]),1)}'
| sort
| tail -1);
echo "$SID"_fs
done
./test_sm.sh: line 11: db1_fs=7: command not found
db1_fs
./test_sm.sh: line 11: db2_fs=7: command not found
db2_fs
./test_sm.sh: line 11: db3_fs=3: command not found
db3_fs
./test_sm.sh: line 11: db4_fs=2: command not found
db4_fs
变量设置为正确的值,但最终的 "echo" 没有给我变量的值(这是我需要的)。相反,它给了我变量名。
来自http://www.tldp.org/LDP/abs/html/ivr.html:
Indirect referencing in Bash is a multi-step process. First, take the name of a variable: varname. Then, reference it: $varname. Then, reference the reference: $$varname. Then, escape the first $: $$varname. Finally, force a reevaluation of the expression and assign it: eval newvar=$$varname.
所以在你的情况下:
eval echo $"$SID"_fs
使用declare
。下面展示了如何设置变量名(使用declare
)和如何检索值(使用间接参数扩展)。
for SID in db1 db2 db3 db4
do
name="${SID}_fs"
value=$(...)
declare "$name=$value"
echo "${!name}"
done
bash
4.3 引入了 namerefs 来简化这个任务。
for SID in db1 db2 db3 db4
do
declare -n sid_fs=${SID}_fs
sid_fs=$(...)
echo "$sid_fs"
done
您也可以考虑使用关联数组,而不是单独的参数。
declare -A fs
for SID in db1 db2 db3 db4; do
fs[$SID]=$(...)
echo ${fs[$SID]}
done
脚本:
#!/bin/bash
for SID in db1 db2 db3 db4
do
"$SID"_fs=$(
df -k
| grep "$SID\/data"
| tr -s ' '
| cut -d' ' -f6
| awk '{print substr([=10=],length([=10=]),1)}'
| sort
| tail -1);
echo "$SID"_fs
done
./test_sm.sh: line 11: db1_fs=7: command not found
db1_fs
./test_sm.sh: line 11: db2_fs=7: command not found
db2_fs
./test_sm.sh: line 11: db3_fs=3: command not found
db3_fs
./test_sm.sh: line 11: db4_fs=2: command not found
db4_fs
变量设置为正确的值,但最终的 "echo" 没有给我变量的值(这是我需要的)。相反,它给了我变量名。
来自http://www.tldp.org/LDP/abs/html/ivr.html:
Indirect referencing in Bash is a multi-step process. First, take the name of a variable: varname. Then, reference it: $varname. Then, reference the reference: $$varname. Then, escape the first $: $$varname. Finally, force a reevaluation of the expression and assign it: eval newvar=$$varname.
所以在你的情况下:
eval echo $"$SID"_fs
使用declare
。下面展示了如何设置变量名(使用declare
)和如何检索值(使用间接参数扩展)。
for SID in db1 db2 db3 db4
do
name="${SID}_fs"
value=$(...)
declare "$name=$value"
echo "${!name}"
done
bash
4.3 引入了 namerefs 来简化这个任务。
for SID in db1 db2 db3 db4
do
declare -n sid_fs=${SID}_fs
sid_fs=$(...)
echo "$sid_fs"
done
您也可以考虑使用关联数组,而不是单独的参数。
declare -A fs
for SID in db1 db2 db3 db4; do
fs[$SID]=$(...)
echo ${fs[$SID]}
done