0

I am trying to control (via multiple IF statements) the integer range of a defined variable within a while loop in Linux.

My Bash Code:

#!/bin/bash

pad=3
START=1
END=246
i=${START}

while [ ${i} -le ${END} ];
do

num=$(printf "%0*d\n" $pad ${i})

echo "${num}"

if [ ${num} -lt "36" ];
then
((i = i + 1))
fi

if [ ${num} -ge "36" ] && [ ${num} -le "192" ];
then
((i = i + 3))
fi

if [ ${num} -ge "192" ] && [ ${num} -le "246" ];
then
((i = i + 6))
fi

done

exit 0

Expected Output:

001
...
...
...
036
039
042
...
...
...
192
198
204
...
...
...
240
246

Terminal Output:

001
...
...
...
036
039
042
...
...
...
192
198
201
204
...
...
...
243
246

After the IF condition has been met, post-192 and pre-246, the ${num} variable is still increasing by 3 instead of increasing by 6.

3
  • 3
    if num is 192, shouldn't it increase by 9? Commented Sep 21, 2020 at 16:43
  • 1
    I don't get the output you show when I run your code. Commented Sep 21, 2020 at 16:45
  • 2
    Are you looking for something like printf '%s\n' {1..36} {39..192..3} {198..246..6}? Commented Sep 21, 2020 at 16:46

1 Answer 1

2

As others have commented, running that code does not produce that output.

Carefully think about what happens in the loop when i == 192 -- you want to be using elif

I'd suggest this:

while (( i <= END )); do
    printf "%0*d\n" $pad ${i}

    if (( i < 36 )); then
        ((i += 1))
    elif (( 36 <= i && i < 192)); then
        ((i += 3))
    else
        ((i += 6))
    fi
done

or this

for (( i=START, incr=1; i <= END; i += incr )); do
    printf "%0*d\n" $pad ${i}
    (( i == 36 )) && incr=3
    (( i == 192)) && incr=6
done
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.