user2561395
user2561395

Reputation: 11

bash script end loop if true

I have an array of numbers (1 2 3 4 5)

magicnumber=7

I want to say if the magic number is equal to a number found in the array or greater than the highest number in the array then do.

{array[@]} - contains numbers

highnum=the highest number from the array

for f in $dir   "#f is file with a number in it"
do 

    "the number inside file f is pulled out and named filenum"
    filenum

    for i in ${array[@]}
    do
        if [ $i -eq $filenum ] || [ $filenum -gt $highnum ]
        then 
            do this and end the "for i loop"
        else
            continue with loop
        fi
    done
done

Upvotes: 0

Views: 78

Answers (1)

glenn jackman
glenn jackman

Reputation: 246877

You can use "array stringification" and pattern matching to determine if the magic number is in the array -- All the quotes and spaces below are very deliberate and necessary.

if [[ " ${array[*]} " == *" $magicnumber "* ]]; then
    echo "magic number is in array"
else
    # Otherwise, find the maximum value in the array 
    max=${array[0]}
    for (( i=1; i<${#array[@]}; i++ )); do
        (( ${array[i]} > max )) && max=${array[i]}
    done
    (( magicnumber > max )) && echo "magic number greater than array elements"
fi

Upvotes: 3

Related Questions