0

For a c-style language for loop the following executes zero times:

for (int myvar = 0; myvar <= -3; myvar++) {
   printf("hi")
}

bash instead will execute the loop four times by going by -1

for j in {0..-3}; do echo 'hi'; done

hi
hi
hi
hi

The following will execute once

for j in {1..4..0}; do echo 'hi'; done

hi

So how to avoid executing the loop short of commenting the entire thing out? I'd like to control this via variables in the loop indices:

first=0
last=-3
step=1
for j in {$first..$last..$step}; do echo 'hi'; done

hi
1
  • The first loop you posted will actually produce a syntax error. Commented May 9, 2022 at 6:54

1 Answer 1

4
for ((j=0; j<=-3; j++)); do
    echo hi
done

for ((j=first; j<=last; j+=step)); do
    echo hi
done
Sign up to request clarification or add additional context in comments.

1 Comment

Oh bash has the c-style looping (albeit with slightly different syntax)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.