1

I expected the following loop to print numbers:

#!/bin/bash
# Basic range in for loop
for value in {1..5}
do
    echo $value
done

but I get the following output in a single line: {1..5}

What am I doing wrong?

Bi Bi
  • 31
  • 3

1 Answers1

1

{1..5} won't necessarily work like you expect it to in every circumstance. A better way to do this (to my mind, at least) is to use seq:

for value in $(seq 1 5)
do
    echo $value
done

seq is a simple program included in basically every Unix that generates the sequence of numbers dictated by its two arguments.

Sebastian Lenartowicz
  • 4,695
  • 4
  • 28
  • 39
  • 1
    For `bash`: Using `seq` for this is overkill. It is wasting a process, for something that is built-in. Use `seq` only if one of them (1 or 5) is a variable. For `sh`: there is no simpler option than `seq`. – anishsane Sep 19 '16 at 07:19
  • @Sebastian thanks for the suggestion. I knew about the seq but I wasn't sure why the curly brackets didn't work. – Bi Bi Sep 19 '16 at 12:48
  • 2
    With bash, the better practice is `for ((i=1; i<5; i++)); do echo "$i"; done`. `seq` is not built into bash, and it is not part of the POSIX specification. There is no guarantee it will exist at all, and if it _does_ exist, there is no guarantee it will behave any particular way. – Charles Duffy Nov 11 '20 at 16:25