【发布时间】:2015-09-17 23:48:46
【问题描述】:
我必须编写一个 bash 脚本,让用户选择要显示的数组元素。
例如,数组有这些元素
ARRAY=(零一二三四五六)
我希望脚本能够在用户输入数组索引后打印出元素
假设用户输入(一行):1 2 6 5
那么输出将是:一二六五
输入的索引可以是单个(输入:0输出:零)或多个(如上),输出将对应索引输入了
非常感谢任何帮助。
谢谢
【问题讨论】:
我必须编写一个 bash 脚本,让用户选择要显示的数组元素。
例如,数组有这些元素
ARRAY=(零一二三四五六)
我希望脚本能够在用户输入数组索引后打印出元素
假设用户输入(一行):1 2 6 5
那么输出将是:一二六五
输入的索引可以是单个(输入:0输出:零)或多个(如上),输出将对应索引输入了
非常感谢任何帮助。
谢谢
【问题讨论】:
ARRAY=(zero one two three four five six)
for i in $@; do
echo -n ${ARRAY[$i]}
done
echo
然后像这样调用这个脚本:
script.sh 1 2 6 5
它会打印出来:
one two six five
【讨论】:
您可能希望将关联数组用于通用解决方案,即假设您的键不只是整数:
# syntax for declaring an associative array
declare -A myArray
# to quickly assign key value store
myArray=([1]=one [2]=two [3]=three)
# or to assign them one by one
myArray[4]='four'
# you can use strings as key values
myArray[five]=5
# Using them is straightforward
echo ${myArray[3]} # three
# Assuming input in $@
for i in 1 2 3 4 five; do
echo -n ${myArray[$i]}
done
# one two three four 5
另外,请确保您使用的是 Bash4(版本 3 不支持它)。详情请见this answer and comment。
【讨论】: