How to Use Bash One Line “while” Loop [8 Examples]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

In Bash, a one-line while loop is a loop construct that fits into a single line of code. When comes to performing a task in the shortest possible time, writing a single-line script instead of a multiline code is a good idea. A single-line code returns the same result as the multiline script, but it is more convenient. In this article, I will cover 8 different examples of Bash one-line while loop so that you can integrate them easily into your task.

Syntax of Bash One Line “while” Loop

A one-line while loop contains the loop condition, body, and termination in a single line, separated by semicolons (;). The syntax of a single-line while loop is:

while [ condition ]; do command; done
EXPLANATION

while [ condition ];: Starts the while loop with a specified condition in square brackets “[]”. The loop continues executing as long as this condition is true.

do: Marks the beginning of the loop body.

command: Command or statement to be executed in each iteration of the loop.

done: Indicates the end of the loop body. The script returns to the while loop, re-evaluates the condition, and continues looping if the condition is still true.

8 Examples of Bash One Line “while” Loop

A multiline while loop code can be written into a single line by following the one-line while loop structure. In this section, I will explain 8 practical examples of using a bash one-line while loop in detail. Let’s dive in.

1. Simple Counter Loop

A simple counter one-line while loop can count the number of iterations of the while loop. It uses the -lt (less than) operator within the loop which is a comparison operator in Bash. Now, follow the script to see how the one-line while loop with counter looks like:

#!/bin/bash
counter=1; while [ $counter -lt 6 ]; do echo $counter; ((counter++)); done
EXPLANATION

This one-liner script initializes a counter variable (counter) to 1 and then enters a while loop. The loop condition ($counter -lt 6) checks if the counter is less than 6. If true, it executes the loop body, which echoes the current value of the counter and increments it by one after each iteration using the ((counter++)). The loop continues as long as the counter is less than 6.

simple counter one line while loop in bash

As you can see the one line while loop has printed the counter’s value between 1 and 5 depending on the condition.

2. Reading Lines from a File

To read a file line using one line while loop, use the read command within the loop that can read a specified file line by line. Incorporating the -r option with the read command prevents the backslashes (\) from being interpreted as escape characters. Now, check out the bash script to learn how to read a file using one-line while loop:

#!/bin/bash
while read -r line; do echo "$line"; done < file.txt
EXPLANATION

while read -r line; do starts a while loop and continues to read each line from the file named “file.txt”. After reading each line, it prints the read line to the standard output with the echo "$line". done < file.txt specifies the end of the while loop and it indicates that the input for the loop is coming from the “file.txt” file. The loop continues until all lines in the file have been read.

reading file line using one line while loop in bash

Upon executing the script, it displays all the read lines from the “file.txt” including backslash characters.

3. Downloading a File with Retry

To download a file using one line while loop, use the wget command inside the loop. The loop repeatedly executes the wget command until the download is successful. Here, a RPM package file of Google Chrome will be downloaded. Follow the bash script to complete the task:

#!/bin/bash
url="https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm"; while ! wget -q $url; do sleep 1; done && echo "Google Chrome package downloaded successfully!"
EXPLANATION

url=”https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm” sets the variable url to the specified URL for the Google Chrome RPM package. while ! wget -q $url; do repeatedly executes the wget command until the download is successful. The -q option makes wget operate in quiet mode, and the ! negates the exit status, so the loop continues as long as the download is unsuccessful.

The sleep 1 pauses for 1 second between attempts before going to the next iteration. && echo "Google Chrome package downloaded successfully!" prints a success message to the terminal only when the download is successful.

downloading a package file using one line while loop in bash

After downloading the package file, check it by running the ls command in the terminal:

checking if the google chrome package file is downloaded

You can see in the image that the Google Chrome rpm package file has been downloaded successfully.

4. Looping Through an Array

An array in Bash is a data structure that stores a set of elements. This example will show how a one-line while loop can be used to iterate through the elements of an array and print each element on a new line in the terminal. To accomplish the task, copy the script:

#!/bin/bash
my_array=("apple" "banana" "orange" "mango"); i=0; while [ $i -lt ${#my_array[@]} ]; do echo ${my_array[$i]}; ((i++)); done
EXPLANATION

my_array=("apple" "banana" "orange" "mango") initializes an array named my_array with 4 elements. i=0 initializes a variable i to 0, which will be used as the index to iterate through the array. while [ $i -lt ${#my_array[@]} ]; do starts a while loop that continues as long as the index i is less than the length of the array my_array. echo ${my_array[$i]} prints the element at the current index of the array. ((i++)) increments the index i in each iteration of the loop.

looping through array using one line while loop in bash

As you can see, each element of the my_array is shown on a new line.

5. Quitting with a Specific User Input

The one-line while loop can be used if a user wants to quit a loop by providing a specific input. In the following script, [[ $num == 'q' ]] checks if the entered value is “q”. If it is, the loop will break with the break statement. Now, check out the entire bash script:

#!/bin/bash
while read -p "Enter a number (or 'q' to quit): " num; do [[ $num == 'q' ]] && break; echo "You entered: $num"; done
EXPLANATION

while read -p "Enter a number (or 'q' to quit): " num; do begins the while loop and prompts the user for input with the read -p command and stores it in the variable num. The loop continues until the user enters “q”. The break command is combined with [[ $num == 'q' ]] condition using the && operator to terminate the loop when the input is “q”.

one line while loop with user input in bash

You can see that when I entered “q”, the loop ended.

6. Monitoring CPU Usage

Here, an infinite one-line while loop is created to continuously monitor the CPU usage. This script includes the date command to display the current date and time. Additionally, the top command extracts and computes the use of the CPU in combination with grep and awk. Here’s how:

#!/bin/bash
while true; do echo "$(date) - CPU Usage: $(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}')"; sleep 1; done
EXPLANATION

while true; do starts an infinite while loop that will keep running until explicitly terminated. echo "$(date) - CPU Usage: $(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}')" prints a message containing the current date and CPU usage to the terminal.

The top -bn1 runs the top command in batch mode (-b) with a single iteration (-n1). In batch mode, the top outputs its data once and exits. The single iteration ensures that the top doesn’t continuously update its output but provides information for a single moment.

grep "Cpu(s)" uses the grep command to filter the output of the top to only include lines containing “Cpu(s)”. The awk '{print $2 + $4}' uses the awk command to extract the values from the second and fourth columns of the filtered line (which correspond to the user and system CPU usage percentages) and adds them together.

one line while loop showing CPU usage

This image displays the CPU usage continuously along with the current date and time.

7. Monitoring Log File Changes

To continuously monitor system log file changes, the inotifywait command is used within the one-line while loop. Whenever any modification occurs, the tail command will print the last line of the file. Here’s how it works:

Note: Before running the script, make sure that you have the “inotify-tools” package installed on your system. If not, run the following command:

For Debian-based distro users:

sudo apt-get install inotify-tools

For red-hat-based distro users:

sudo yum install inotify-tools
#!/bin/bash
file="/var/log/syslog"; while inotifywait -e modify "$file"; do tail -n 1 "$file"; done
EXPLANATION

Here, file="/var/log/syslog" defines a variable named file and sets its value to the path of the “/var/log/syslog” file. while inotifywait -e modify "$file"; do starts a loop that continuously monitors the file for modifications using the inotifywait command. The option -e modify specifies that the script should respond to modification events. When a modification is detected, it prints the last line of the file using tail -n 1.

monitoring file changes using one line while loop in bash

You can see the last line of the “syslog” file in real-time whenever there is a change.

8. Running a Command Until Successful

The ping command is incorporated with the while loop in this example to check the reachability of the server “linuxsimply.com”. The while loop continuously executes the command until the command is successful. Here’s the complete bash script:

#!/bin/bash
while ! ping -c1 linuxsimply.com; do echo "Waiting for network..."; sleep 5; done
EXPLANATION

After starting a while loop, the condition ! ping -c1 linuxsimply.com within the loop checks whether the ping command to “linuxsimply.com” fails (returns a non-zero exit code). If the ping command fails, it echoes “Waiting for network…” in the terminal by the echo command. sleep 5 is used to pause the script for 5 seconds before the next iteration of the loop.

one line while loop running until a command is successful

The ping command is successfully executed as shown in the picture.

Practice Tasks of Bash One Line “while” Loop

Practice the following to improve your understanding of how to use a one-line while loop in bash scripting:

  1. Create a one-liner Bash script that uses a “while” loop to implement a countdown timer. The loop should display the remaining seconds every second, starting from 10 down to 1.
  2. Write a one-liner Bash code that uses a “while” loop to repeatedly prompt the user for input. The loop should continue indefinitely until the user enters the word “exit”.
  3. Make a bash one-liner “while” loop that runs a command for 15 seconds, displaying a message every second.
  4. Generate a bash script using one line “while” loop that guesses a random number between 1 and 100 in 5 attempts.

Conclusion

In conclusion, I hope that this article has helped you understand the basic concepts and applications of bash one line while loop. In this article, I have provided 8 examples of one line while loop in bash. To enhance your skills, make sure to perform the practice tasks. Have a great day!

People Also Ask

How do you run a command in an endless loop in Bash?

In Bash, to run a command in an endless loop, you can write the command inside the while true structure. Here’s a basic example:

#!/bin/bash
while true; do
echo "Running command in an endless loop..."
sleep 1  # Adjust the sleep duration as needed
done

This script repeatedly runs the “Running command in an endless loop…” until it is explicitly stopped by pressing CTRL+C.

How do I skip a loop in Bash?

To skip a loop in Bash, you can use the continue command with conditional statements to skip certain iterations based on specific conditions. The continue statement skips the rest of the current iteration and moves to the next one in a loop.

How do you break a line in Bash?

To break a line in Bash, you can use a backslash \ at the end of the line (where you wish to break). Here’s an example:

#!/bin/bash
echo "This is a long \
line of text in Bash."

Output:

This is a long line of text in Bash.

How do you write a while loop in Bash?

In Bash, you can write a while loop to repeatedly execute a block of code as long as a specified condition is true. The basic syntax for a while loop in Bash is as follows:

while [ condition ]; do
# Code to be executed while the condition is true
done

Is there a do while loop in Bash?

There isn’t a do-while loop in bash in the traditional sense as found in some other programming languages. However, you can achieve a similar result using the while loop with an initial condition that is always true and then using a conditional break statement to exit the loop when a specific condition is met.

What is bash one line infinite loop?

A one-line infinite loop in Bash is achieved using the while true construct. The true command always returns a true value, resulting in an infinite loop. Here’s the syntax:

while true; do echo "This is an infinite loop"; sleep 1; done

Related Articles


<< Go Back to “while” Loop in Bash | Loops in Bash | Bash Scripting Tutorial

Rate this post
Mitu Akter Mou

Hello, This is Mitu Akter Mou, currently working as a Linux Content Developer Executive at SOFTEKO for the Linuxsimply project. I hold a bachelor's degree in Biomedical Engineering from Khulna University of Engineering & Technology (KUET). Experiencing new stuff and gathering insights from them seems very happening to me. My goal here is to simplify the life of Linux users by making creative articles, blogs, and video content for all of them. Read Full Bio

Leave a Comment