我遇到了打印出索引和数组项的脚本的问题,然后允许用户输入将打印出该数组的特定项的索引。
array=(abc def ghi)
i=0
while [ $i -lt ${#array[*]} ]; do
echo "[$i] ${array[$i]}"
i=$(($i+1));
done
echo -e "select an index: "; read answer
#this is the part that is troubling me
for index in ${!array[*]}; do
if [[ $answer == $index ]]; then
echo ${array[$index]}
break
else
echo "invalid"
break
fi
done
所以如果用户输入0,它应该打印abc。 1将是def等。它目前仅适用于指数0.
答案 0 :(得分:0)
我可以找到一些问题:
正在运行的代码应如下所示:
array=(abc def ghi)
i=0
while [ $i -lt ${#array[*]} ]; do
echo "[$i] ${array[$i]}"
i=$(($i+1));
done
echo -e "select an index: "; read answer
for index in ${!array[*]}; do
found="FALSE"
if [[ "$answer" == "$index" ]]; then
found="TRUE"
echo "${array[$index]}"
break
fi
done
if [ "$found" == "FALSE" ]; then
echo "Invalid input $answer"
fi