Using the `while` Command (with examples)

Using the `while` Command (with examples)

The while command is a powerful tool in shell scripting that allows you to execute a set of commands repeatedly as long as a certain condition is true. It provides a flexible way to automate tasks and perform actions based on the output or input of a script. In this article, we will explore eight different use cases of the while command and provide code examples to illustrate each scenario.

Use Case 1: Read stdin and perform an action on every line

while read line; do
  echo "$line"
done

Motivation: This use case is helpful when you want to process each line from the standard input (often piped from another command) and perform an action on each line.

Explanation: The while loop reads input from stdin using the read command, which assigns each line to the variable line. The loop then executes the echo command, which prints the value of line.

Example Output: If we have a file input.txt with the following content:

apple
banana
orange

Running the code cat input.txt | while read line; do echo "$line"; done will produce the following output:

apple
banana
orange

Use Case 2: Execute a command forever once every second

while :; do
  command
  sleep 1
done

Motivation: This use case is useful when you want to execute a specific command continuously at a regular interval, such as for monitoring or polling purposes.

Explanation: The while loop uses the : (null command) as its condition, which is always true. Inside the loop, you can replace command with the desired command to execute. The sleep 1 command pauses the loop for one second before executing the command again.

Example Output: Let’s say we want to print the current timestamp every second. Running the code while :; do date; sleep 1; done will produce the following output, updated every second:

Wed Nov 10 15:45:02 UTC 2021
Wed Nov 10 15:45:03 UTC 2021
Wed Nov 10 15:45:04 UTC 2021
...

Use Case 3: Read lines from a file and perform an action on each line

while IFS= read -r line; do
  command
done < file.txt

Motivation: This use case is helpful when you want to read lines from a file and perform an action on each line.

Explanation: The while loop reads each line from the file file.txt by redirecting it as the input using the < operator. The IFS= part is used to preserve leading and trailing whitespaces in each line. The read command assigns each line to the variable line, and you can perform desired actions within the loop using command.

Example Output: Assuming we have a file named numbers.txt with the following content:

1
2
3

Running the code while IFS= read -r line; do echo "Number: $line"; done < numbers.txt will produce the following output:

Number: 1
Number: 2
Number: 3

Use Case 4: Iterate over an array and perform an action on each element

array=("apple" "banana" "orange")
index=0

while [ $index -lt ${#array[@]} ]; do
  element="${array[index]}"
  command
  index=$((index + 1))
done

Motivation: This use case is beneficial when you want to iterate over an array in bash and perform an action on each element of the array.

Explanation: The while loop iterates over the array by using an index variable (index). It checks if the index is less than the length of the array using the -lt (less than) operator. Inside the loop, the element at the current index is retrieved using ${array[index]}, and you can perform desired actions using command. Finally, the index is updated by incrementing it.

Example Output: Running the following code will print each element of the array array:

array=("apple" "banana" "orange")
index=0

while [ $index -lt ${#array[@]} ]; do
  element="${array[index]}"
  echo "Fruit: $element"
  index=$((index + 1))
done

The output will be:

Fruit: apple
Fruit: banana
Fruit: orange

Use Case 5: Read command output and perform an action

command | while IFS= read -r line; do
  command
done

Motivation: This use case is useful when you want to process the output of a command line by line and perform an action on each line.

Explanation: The while loop reads the output of the command using a pipe (|) and the read command. Each line is then assigned to the variable line. You can perform desired actions within the loop using command.

Example Output: Assuming we have a command list_files that lists all the files in the current directory. Running the code list_files | while IFS= read -r line; do echo "File: $line"; done will produce the following output:

File: file1.txt
File: file2.txt
File: file3.txt
...

Use Case 6: Execute a command until a condition is met

while condition; do
  command
done

Motivation: This use case is helpful when you want to execute a command repeatedly until a certain condition is met.

Explanation: The while loop continues executing as long as the condition is true. Inside the loop, you can place command to perform the desired action. The condition can be any valid condition in bash, such as using comparison operators or checking the exit status of a command.

Example Output: Let’s say we want to wait until a specific file is created in the current directory. Running the following code will continuously check if the file target_file.txt exists and print a message when it is found:

while [ ! -f "target_file.txt" ]; do
  echo "Waiting for target file..."
  sleep 1
done
echo "Target file found!"

The code will output:

Waiting for target file...
Waiting for target file...
Waiting for target file...
...
Target file found!

Use Case 7: Read input from a file descriptor

while IFS= read -r -ufd line; do
  command
done fd< file.txt

Motivation: This use case is useful when you want to read input from a specific file descriptor (fd) and perform an action on each line.

Explanation: The while loop reads each line from the file descriptor fd using the -u option of the read command. The file descriptor can be any valid file descriptor number. The IFS= part is used to preserve leading and trailing whitespaces in each line. You can perform desired actions within the loop using command.

Example Output: Assuming we have a file named data.txt with the following content:

line 1
line 2
line 3

Running the following code will read the content of data.txt from file descriptor 3 and print each line:

while IFS= read -r -u3 line; do
  echo "Line: $line"
done 3< data.txt

The output will be:

Line: line 1
Line: line 2
Line: line 3

Use Case 8: Use until instead of while to invert the condition

until condition; do
  command
done

Motivation: This use case is helpful when you want to execute a command repeatedly until a certain condition is false.

Explanation: The until loop behaves similarly to the while loop, but it continues executing until the condition becomes false. Inside the loop, you can place command to perform the desired action. The condition can be any valid condition that evaluates to true or false in bash.

Example Output: Let’s say we want to repeatedly prompt the user for input until a valid number is entered. Running the following code will prompt the user for input and check if the input is a valid number using a regular expression:

until [[ $input =~ ^[0-9]+$ ]]; do
  read -p "Enter a number: " input
done
echo "Valid number entered: $input"

The code will keep prompting the user until a valid number is entered, and then output the entered number.

Conclusion

The while command provides a flexible way to create loops in shell scripting, allowing you to repeat commands based on conditions. In this article, we explored eight different use cases of the while command, providing code examples, motivations, explanations, and example outputs for each scenario. With these examples, you can leverage the power of the while command to automate tasks and perform actions effectively in your shell scripts.

Related Posts

How to use the command "pacman --upgrade" (with examples)

How to use the command "pacman --upgrade" (with examples)

Pacman is the package manager utility for Arch Linux. It is used to install, upgrade, and manage packages on an Arch Linux system.

Read More
How to use the command 'postconf' (with examples)

How to use the command 'postconf' (with examples)

The ‘postconf’ command is a postfix configuration utility that allows users to display and change the values of the main.

Read More
How to use the command wifi-password (with examples)

How to use the command wifi-password (with examples)

The wifi-password command is a useful tool that allows users to retrieve the password for the Wi-Fi network they are currently connected to.

Read More