0

I'm playing with bash scripts. I want to loop through a range starting at 1, and for now, just ending at 5. (would like to accept inputs but I can do that in a bit).

#!/bin/sh

for i in {1..5}
do
    echo "i is now $i"
done

My current bash version is 4.4.20(1)-release

Why is this not looping through the provided range? Is this not correct syntax?

Squid
  • 5
  • 1
  • @Cyrus That dupe seems totally unrelated. – Joseph Sible-Reinstate Monica Feb 21 '20 at 22:20
  • @JosephSible-ReinstateMonica: okay. I reopend this question. – Cyrus Feb 21 '20 at 22:21
  • @thatotherguy It was [How can I just extract one underbar-separated field from a filename?](https://stackoverflow.com/q/60346648/7509065). Yours does seem more reasonable, if still a bit broad. – Joseph Sible-Reinstate Monica Feb 21 '20 at 22:28
  • 1
    @JosephSible-ReinstateMonica, ...I've edited [Loop of form “for i in {1..171}” not working (only loops once, with i='{1..171}')](https://stackoverflow.com/questions/20015611/loop-of-form-for-i-in-1-171-not-working-only-loops-once-with-i-1-171) to make its title directly and obviously on-point. – Charles Duffy Feb 21 '20 at 22:31

1 Answers1

1

{1..5} is a bash-ism, but your shebang line indicates sh. Use $(seq 1 5) instead if you want to use sh, or just switch to bash.

  • 2
    If you are using `sh` because you want to guaranteed POSIX compatibility, be aware that `seq` is not defined by POSIX. The POSIX way to iterate over a sequence of numbers is to use a `while` loop: `i=1; while [ "$i" -le 5 ]; do echo "$i"; i=$((i+1)); done`. – chepner Feb 21 '20 at 22:24
  • Oh I see. I was definitely misinformed about the use of shebang. Your solution works! I will accept your answer as soon as it lets me. – Squid Feb 21 '20 at 22:25