Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping over a Bash array: getting the next element in the middle of the loop

Searching an array (lines_ary[@]) which has read a file into it, I'm trying to find a version number in the text. Here I am looking for Release, so I can find the version number that follows.

Is there any way to access the next element in an array in a bash script when doing the following loop?

for i in ${lines_ary[@]}; do
 if [ $i == "Release:" ] ; then
  echo ${i+1}
 fi
done

This just prints out '1', rather than say '4.4'.

like image 283
kjbradley Avatar asked Jun 11 '13 20:06

kjbradley


2 Answers

You need to loop on an index over the array rather than the elements of the array itself:

for ((index=0; index < ${#lines_ary[@]}; index++)); do
  if [ "${lines_ary[index]}" == "Release:" ]; then
    echo "${lines_ary[index+1]}"
  fi
done

Using for x in ${array[@]} loops over the elements rather than an index over it. Use of the variable name i is not such a good idea because i is commonly used for indexes.

like image 64
Michael Hoffman Avatar answered Oct 16 '22 06:10

Michael Hoffman


Assuming the lines array looks something like

array=("line 1" "Release: 4.4" "line 3")

Then you can do:

# loop over the array indices
for i in "${!array[@]}"; do
    if [[ ${array[i]} =~ Release:\ (.+) ]]; then
        echo "${BASH_REMATCH[1]}"   # the text in the capturing parentheses
        break
    fi
done

output:

4.4
like image 45
glenn jackman Avatar answered Oct 16 '22 04:10

glenn jackman