Create One Line Loop in Bash

This article will explain how we can create one-line loops in Linux Bash. We will write example scripts with the for loop.

Create One Line Loop in Linux Bash

We can create simple one-line loops in different ways as follows.

Write Each Element Inside the Loop

We can write the elements in the loop one by one.

for i in "apple" "banana" "orange"; do echo "$i"; done

For loop with elements

Specify a Range of Numbers

A range of numbers can be used to create a one-line loop.

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

For loop with elements

Create Loop With Subcommand

We can use subcommands to specify the values used in the loop. This method is especially useful for reading file contents.

for i in `seq 1 3`; do echo "step: $i"; done;
for i in `cat file.txt`; do echo "step: $i"; done;

For loop with subcommand

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Bash Loop

  • Loop Through Array in Bash