How to write a for loop to perform an operation N times in the ash shell?

Viewed 669

I'm looking to run a command a given number of times in an Alpine Linux docker container which features the /bin/ash shell.

In Bash, this would be

bash-3.2$ for i in {1..3}
> do
> echo "number $i"
> done
number 1
number 2
number 3

However, the same syntax doesn't seem to work in ash:

> docker run -it --rm alpine /bin/ash
/ # for i in 1 .. 3
> do echo "number $i"
> done
number 1
number ..
number 3
/ # for i in {1..3}
> do echo "number $i"
> done
number {1..3}
/ # 

I had a look at https://linux.die.net/man/1/ash but wasn't able to easily find out how to do this; does anyone know the correct syntax?

2 Answers

I ended up using seq with command substitution:

/ # for i in $(seq 10)
> do echo "number $i"
> done
number 1
number 2
number 3
number 4
number 5
number 6
number 7
number 8
number 9
number 10

Another POSIX compatible alternative, which does not use potentially slow expansion, is to use

i=1; while [ ${i} -le 3 ]; do
  echo ${i}
  i=$(( i + 1 ))
done
Related