0

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
5
  • Welcome to Stack Overflow. To indent the code, write it in the text edit box (or paste it) as you want it to appear — no tabs. Then select the code and press the {} button above the edit box to indent all by 4 spaces. Commented Mar 29, 2014 at 16:56
  • The break statement terminates the loop. The else clause is redundant since the loop will continue anyway. However, you could use continue in the else clause to go to the next cycle of the loop. Commented Mar 29, 2014 at 16:57
  • If I am looping in a loop will it break both or just the last loop? Commented Mar 29, 2014 at 18:11
  • @user2561395: Typing help break in a bash shell will provide faster feedback then adding comments to an SO question. Commented Mar 29, 2014 at 19:19
  • 1
    On its own, break breaks a single loop; to break 2 levels of loop, you'd say break 2. Similarly with continue. Commented Mar 29, 2014 at 20:08

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.