简体   繁体   中英

Control Integer Range of a Defined Variable Within While Loop

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM