BASH数组索引减去最后一个数组 [英] BASH Array indexing minus the last array
问题描述
这是一个困扰我的问题-我需要从用户输入中读取版本号,并且我想使用存储版本号的数组的长度创建一个菜单".但是,BASH的神秘语法在这里没有帮助我
Here is a problem which bothers me - I need to read version number from user input, and I'd like to create a "menu" using the length of the array storing the version numbers. However, BASH's mysterious syntax is not helping me here:
echo $VERSIONS
2.0.10-1 2.0.7-1 2.0.7-1 2.0.7-1 2.0.10-1
for v in ${!VERSIONS[*]}
do
echo "$(($v+1))) ${VERSIONS[$v]} "
done
输出
1) 2.0.10-1
2.0.7-1
2.0.7-1
2.0.7-1
2.0.10-1
2) 2.0.7-1
3) 2.0.7-1
4) 2.0.7-1
5) 2.0.10-1
另一个命令
for v in ${!VERSIONS[*]}
do
echo "$(($v+1))) ${VERSIONS[$v+1]} "
done
1) 2.0.7-1
2) 2.0.7-1
3) 2.0.7-1
4) 2.0.10-1
5)
我真正想要的是这样的输出:
What I'd really like to have is an output like that:
1) 2.0.7-1
2) 2.0.7-1
3) 2.0.7-1
4) 2.0.10-1
不含最后5个)....
with out the last 5)....
很乐意在bash中阐明如何做...
Would be happy to unravel how to do it in bash...
P.S.我的一位同事刚刚提供了一种没有阵列的方法.我发布它只是为了好玩:
P.S. A colleague of mine just offered a way without arrays. I'm posting it just for fun:
i=1
for v in $VERSIONS
do
echo "$i) $v" ; i=$(($i+1))
done
输出
1) 2.0.10-1
2) 2.0.7-1
3) 2.0.7-1
4) 2.0.7-1
5) 2.0.10-1
好的,由于解决方案无法在我的脚本内运行,因此我将发布更多信息:
OK, since the solutions don't work inside my script I will post some more info:
for package in $NEWPACKAGES
do
apt-show-versions -a -p $package
VERSIONS=$(apt-show-versions -a -p $package | cut -d ":" -f 2 | cut -d " " -f 1)
echo $VERSIONS
echo "type the number for version you want to install: (type enter to skip)"
for i in `seq 1 ${#VERSIONS[@]}`; do
echo "$i) ${VERSIONS[$(($i-1))]}";
done
echo $VERSIONS
read version
echo "your choice $version"
# now the problem is that i can't get this part to work !
apt-get install $package="${#VERSIONS[$version]}"
done
推荐答案
一个包含数组的版本(如果仍需要的话).
A version with arrays, if you still need one.
for i in `seq 1 ${#VERSIONS[@]}`; do
echo "$i) ${VERSIONS[$(($i-1))]}";
done
这篇关于BASH数组索引减去最后一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!