oz123
oz123

Reputation: 28898

BASH Array indexing minus the last array

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

output

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   

another command

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 

with out the last 5)....

Would be happy to unravel how to do it in bash...

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

output

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

Upvotes: 3

Views: 4227

Answers (3)

Mu Qiao
Mu Qiao

Reputation: 7107

So indeed you are looking for a away to convert a normal variable to an array, here it is:

array=($VERSIONS)

Upvotes: 1

ghostdog74
ghostdog74

Reputation: 343181

VERSIONS=(2.0.10-1 2.0.7-1 2.0.7-1 2.0.7-1 2.0.10-1) 
for i in ${!VERSIONS[@]} ; do echo "$(($i+1))] ${VERSIONS[i]}"; done

Upvotes: 0

Šimon Tóth
Šimon Tóth

Reputation: 36451

A version with arrays, if you still need one.

for i in `seq 1 ${#VERSIONS[@]}`; do 
    echo "$i) ${VERSIONS[$(($i-1))]}"; 
done

Upvotes: 3

Related Questions