Loop bash command in one line

Sometimes I want to repeat a command in the terminal and I always forget how to do it ๐Ÿ˜‘. To be clear about it this will execute the command and wait for it to complete until it starts the next. No async stuff here!

For loop:

for i in {1..3}; do echo $i; done

For simple cases when you just want to loop over something a number of times. I think itโ€™s the most easily read.

While loop with piped input:

printf "%s\n" {1..3} | while read i; do
  echo $i;
done

While loop with input from Herestrings. Itโ€™s taking the string you put after <<< into stdin. Even more verbosive than the first while loop.

while read i; do
  echo $i;
done <<< "$(printf "%s\n" {1..3})"

One good thing about Herestrings is that they do not create a subshell as the piping method does. If you care about that. Obviously, I donโ€™t in my example because I create a subshell with the command substitution: $() anyway ๐Ÿ˜ฎ.

Resource