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

4

6

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?

Furr answered 28/1, 2022 at 21:20 Comment(0)
F
6

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
Furr answered 28/1, 2022 at 21:23 Comment(0)
L
1

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
Lucrecialucretia answered 13/9, 2022 at 14:37 Comment(1)
As of today, I would not write [] brackets and instead use the POSIX inbuild test to prevent invalid expansions etc on missing spaces.Lucrecialucretia
I
1

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
Intemperate answered 28/9, 2022 at 7:17 Comment(0)
B
0

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.

Blackguardly answered 28/7, 2023 at 3:19 Comment(1)
You should not post comments or thanks as answers. Instead, vote up the answers that helped you.Pursuit

© 2022 - 2024 — McMap. All rights reserved.