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
WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560

1 Answers1

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

for ((j=first; j<=last; j+=step)); do
    echo hi
done
pjh
  • 6,388
  • 2
  • 16
  • 17