How to Create One Line Loop in Bash

Yahya Irmak Feb 02, 2024
How to 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

Author: Yahya Irmak
Yahya Irmak avatar Yahya Irmak avatar

Yahya Irmak has experience in full stack technologies such as Java, Spring Boot, JavaScript, CSS, HTML.

LinkedIn

Related Article - Bash Loop