连接 $ 和 var 时不显示 var 的值 --> $var
Value of var is not shown when concatenating $ and var --> $var
到目前为止,我在 bash 中获得了大约一天的经验..
string () {
for (( i=0; i<${#1}; i++ ))
do
echo "$"${1:$i:1}""
done
}
string "hello"
这个脚本returns "$h
", "$e
", "$l
", "$l
", "$o
",
但我实际上希望它 return 变量 h
、e
、l
、l
和 o
.
的内容
我该怎么做?
您需要使用间接参数扩展:
for ((i=0; i<${#1}; i++)); do
t=${1:i:1}
echo "${!t}"
done
${!t}
获取 $t
的值,并将其视为要扩展的参数名称。
一行使用eval
安全地写出一系列echo
输出bash
参数转换赋值语句,用GNU grep
分割输入字符串:
h=foo o=bar
string() { eval $(printf 'echo ${%s@A};\n' $(grep -o . <<< "$@" )) ; }
string hello
输出,(空行代表未设置的变量$e
和$l
):
h='foo'
o='bar'
到目前为止,我在 bash 中获得了大约一天的经验..
string () {
for (( i=0; i<${#1}; i++ ))
do
echo "$"${1:$i:1}""
done
}
string "hello"
这个脚本returns "$h
", "$e
", "$l
", "$l
", "$o
",
但我实际上希望它 return 变量 h
、e
、l
、l
和 o
.
我该怎么做?
您需要使用间接参数扩展:
for ((i=0; i<${#1}; i++)); do
t=${1:i:1}
echo "${!t}"
done
${!t}
获取 $t
的值,并将其视为要扩展的参数名称。
一行使用eval
安全地写出一系列echo
输出bash
参数转换赋值语句,用GNU grep
分割输入字符串:
h=foo o=bar
string() { eval $(printf 'echo ${%s@A};\n' $(grep -o . <<< "$@" )) ; }
string hello
输出,(空行代表未设置的变量$e
和$l
):
h='foo'
o='bar'