我想更改 bash 循环中使用的变量。我希望第一次迭代回显“/path/to/lol/hello_foo”和第二次“/path/to/lol/hello_bar”。
但相反,这是打印出来的:
/path/to/lol/fname_one
/path/to/lol/fname_two
这是代码:
#!/bin/bash
path_data='/path/to/lol'
fname_one='hello_foo'
fname_two='hello_bar'
for count in one two
do
echo $path_data/fname_$count
done
您可以使用间接变量扩展来做到这一点:
...
fname_var=fname_$count
echo "$path_data/${!fname_var}" # Quoting variable references is a good idea
...
但是对于这样的事情,通常最好使用数组:
#!/bin/bash
path_data='/path/to/lol'
declare -a fname # Make fname an array, rather than a plain variable
fname[1]='hello_foo'
fname[2]='hello_bar'
for count in 1 2
do
echo "$path_data/${fname[count]}"
done
如果您需要文本(非数字)索引,您可以使用关联数组(仅适用于 bash v4):
#!/bin/bash
path_data='/path/to/lol'
declare -A fname # Capital -A makes an associaltive array
fname[one]='hello_foo'
fname[two]='hello_bar'
for count in one two
do
echo "$path_data/${fname[$count]}"
done
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句