Kurt Peek
Kurt Peek

Reputation: 57711

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

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?

Upvotes: 6

Views: 6884

Answers (4)

Konoha Yuminaga
Konoha Yuminaga

Reputation: 1

I am using qemu and only the busybox shell command,in that case,for i in {1..3} does not work,but for i in $(seq 10) is ok,thanks for your question.

Upvotes: 0

paskaloo
paskaloo

Reputation: 11

Simply like with bash or shell:

$ ash -c "for i in a b c 1 2 3; do echo i = \$i; done"

output:

    i = a
    i = b
    i = c
    i = 1
    i = 2
    i = 3

Upvotes: 1

Jay-Pi
Jay-Pi

Reputation: 428

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

Upvotes: 1

Kurt Peek
Kurt Peek

Reputation: 57711

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

Upvotes: 6

Related Questions