0

So I want to pass a for loop in my bash script, and I want it to stop depending on two parameters:

for (( x=1; x<= 50 -a $array_position -lt ${#array[@]}; x++ ))
do
    echo ${array[$array_position]}
    array_position=$((array_position+1))
done

My intention is to have this for loop echo 50 consecutive array values [0] -- [50], but stop if $array_position reaches the end of the array before all 50 loop iterations complete.

Any help is appreciated, as always!

2 Answers 2

1

The problem is the -a or -lt in your for statement. Change it to this:

for (( x=1; x<= 50 && $array_position < ${#array[@]}; x++ ))

Or to simplify the whole thing further:

for (( x=0;  x < 50 && x < ${#array[@]}; x++ ))
do
    echo "${array[$x]}"
done
Sign up to request clarification or add additional context in comments.

1 Comment

This worked great, and solved my question of passing multiple parameters. Thanks!
0

You should only need to specify the array size as your test, and use a break statement if you reach 50:

for (( x=1; x<=${#array[@]}; x++ ))
do
    echo ${array[$array_position]}
    array_position=$((array_position+1))
    [ $x -eq 50 ] && break
done

2 Comments

I agree this is a good idea, but I would like to be able to pass multiple parameters for future use
dogbanes's solution is better in my opinion

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.