1

How do I iterate over a range of numbers in Bash when the range is given.

my code is like

for i in {1..5}
do
   echo "Welcome $i times"
done

And I am expecting

Welcome 1 times
Welcome 2 times
...

However I got something like

Welcome {1..5} times

my bash version is

GNU bash, version 5.0.3(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2019 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
Hugo hu
  • 11
  • 1
  • 2
    That will happen if you are really missing `#!/bin/bash` as the first line and it ends up using `sh` instead of `bash`. Is that really your full code or you didn't paste in the first line? – kaylum Jun 14 '20 at 05:42
  • Ah! That is exactly the reason! Thanks! – Hugo hu Jun 14 '20 at 05:46
  • Possible duplicate: https://stackoverflow.com/questions/21288175/bash-foreach-loop-works-differently-when-executed-from-sh-file (can happen to anyone) – anjsimmo Jun 14 '20 at 06:25

1 Answers1

3

Script is missing the first line:

#!/bin/bash

Result is that a different shell may be running the script. In particular the error will occur if the script is run by sh. This is because {1..5} is a bash sequence expression and is not supported by some other shells like sh.

kaylum
  • 13,833
  • 2
  • 22
  • 31