0

I have a C++ code which I want to convert into POSIX sh code:

for(int j=(i-(i%9)); j<((i-(i%9))+9); j++)
{
    ...
}

My question is that how can I convert this for lopp into POSIX shell? This doesn't work:

for j in {{$i-($i%9)..{($i-(i%9)+9)}}
do
    echo $j;
done
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • 1
    Don't include images in your code -- copy/paste actual text. That way StackOverflow's own syntax highlighting can work, and people using screen-readers or text-based browsers can actually read your question (and, moreover, the question stays usable even if the link to your image breaks). – Charles Duffy Nov 12 '15 at 21:22
  • ...also, even with numbers hardcoded, `{{1..9}}`-type brace expansions are a bashism, not guaranteed to be available in `/bin/sh`. – Charles Duffy Nov 12 '15 at 21:33

1 Answers1

4

If your shell is /bin/bash (as the question initially indicated), with far fewer changes than you think you need, since bash supports C-style for loops. A more compressed syntax is possible with some releases, but to be safe across parser versions, being generous with whitespace is well-advised:

for (( j = ( i - ( i % 9) ); j < ( ( i - ( i % 9 ) ) + 9 ); j++ )); do echo "$j"; done

With /bin/sh, by contrast:

j=$(( i - ( i % 9 ) ))
while [ "$j" -lt "$(( ( i - ( i % 9 ) ) + 9 ))" ]; do
  echo "$j"
  j=$(( j + 1 ))
done

As for your original attempt, brace expansions happen very early in the parsing process -- before any variables' values have been evaluated; consequently, they can't be used with any numbers that aren't static.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441