1. This is what you wrote with a little tweaking.
#!/bin/bash NOME=$1 #IF NAME IS FOUND IN THE PHONE-BOOK **THEN** READ THE PHONE BOOK LINES INTO AN ARRAY VARIABLE #ONCE THE ARRAY IS COMPLETED, GET THE INDEX OF MATCHING LINE AND RETURN ARRAY[INDEX+1] c=0 if grep "$NOME" /root/phonebook.txt ; then echo "CREATING ARRAY...." IFS= while read -r line #IFS= in case you want to preserve leading and trailing spaces do myArray[c]=$line # put line in the array c=$((c+1)) # increase counter by 1 done < /root/phonebook.txt for i in ${!myArray[@]}; do if myArray[i]="$NOME" ; then echo ${myArray[i+1]} >> /root/numbertocall.txt fi done else echo "Name not found" fi
2. But you can also read the array and stop the loop this way:
#!/bin/bash NOME=$1 c=0 if grep "$NOME" /root/phonebook.txt ; then echo "CREATING ARRAY...." readarray myArray < /root/phonebook.txt for i in ${!myArray[@]}; do if myArray[i]="$NOME" ; then echo ${myArray[i+1]} >> /root/numbertocall.txt break
3.- The following improves the situation. Suppose a) $ NAME matches the entire line containing it, and b) there is always one line after the found $ NOME, this will work; if not (if $ NOME might be the last line in the phone book), then you need to make small adjustments.
!/bin/bash PHONEBOOK="/root/phonebook.txt" NUMBERTOCALL="/root/numbertocall.txt" NOME="$1" myline="" myline=$(grep -A1 "$NOME" "$PHONEBOOK" | sed '1d') if [ -z "$myline" ]; then echo "Name not found :-(" else echo -n "$NOME FOUND.... " echo "$myline" >> "$NUMBERTOCALL" echo " .... AND SAVED! :-)" fi exit 0
source share