For loop eases to achieve a specific task done repeatedly for a particular time. The one-line for loop in bash concept makes the code concise and readable. Sometimes, when the condition is a complex or long expression, and the code contains multiple commands on code blocks, it can be organized using a semicolon(;) after each command. In this article, I will explore writing for loop in one line.
One Line “for” Loop Over Multiline Traditional βforβ Loop
The primary notion of βOne Line for Loop Over Multiline Traditional For Loopβ is related to code readability. It means expressing a loop traditionally written in multiple lines as a single line.
Here are some reasons behind preferring the one-line command approach:
- Readability: One line for loop code is concise and easy to read. However, the traditional multiline for loop might be more presentable and organized with proper code indentation for complex logic or longer iterations.
- Conciseness: Writing a loop in a single line makes code compact, reducing the line number of code.
- Code Golfing: One line for loop is preferable for competitive programmers and code golfers who create with the target of a minimized number of characters.
Check the two syntaxes below to know how traditional for loop differs from one line for loop command:
The Syntax for the traditional βforβ Loop is:
for variable in value1 value2 value3 ... valueN
do
[commands to be executed for each iteration]
done
The Syntax for one line βforβ Loop command is:
for i in (list); do command1; command2; done
7 Examples of Bash βforβ Loop in One Line
One line bash for loop command can run a command for a specific time, manage command substitution, loop through an explicit list, and search for files containing particular name patterns. In this section, I have listed some examples related to these:
1. Run a Command 5 Times with One Line βforβ Loop Command
The for loop can efficiently run a command for specific times if the command is placed inside the code block section of the one-line for loop.
Execute the command on the terminal:
for i in {1..5}; do echo "Good Morning, $i"; done
for i in {1..5}; do
starts a for loop initializing a variable i and iterates over the values from 1 to 5. Then, the echo command prints ‘Good Morning [current value of i]’ on each iteration.
C-style βforβ Loop in One Line
The C-style βforβ loop can do the same task in one line command. Here is the code to do so:
for ((c = 1; c <= 5; c++)); do echo "Number: $c"; done
for ((c = 1; c <= 5; c++));
is the syntax for a C-style for loop in Bash. It initializes a variable βcβ to 1 and sets the loop condition to βc is less than or equal to 5β. Then, the c++
increases the value of c by one for each iteration. Finally, the echo command prints the value of c on each iteration.
2. Command Substitution in One Line βforβ Loop
Command substitution means using the output of a command as an input for another command. Combining command substitution with a for loop in a single line enables it to iterate through a list of contents of a file. Below is a list of days inside the weekdays.txt file:
weekdays.txt:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Now run the below code to print each day of the week on the terminal:
for w in $(cat weekdays.txt); do echo "Today is $w"; done
for w in $(cat weekdays.txt); do
initiates a for loop that iterates over the contents of the weekdays.txt file and keeps it on w variable. Finally, the echo command prints the value of w on the terminal.
3. Looping Through Explicit List
For loop can iterate through an explicit list. This explicit list might store customized data. Keeping the list on the for loop iteration entity list helps to print the list’s contents on the terminal.
Execute the below command to print a list of fruits:
for f in Apple Orange Grape Banana; do echo "Fruit: $f"; done
for f in Apple Orange Grape Banana; do
initialize a for loop in Bash that iterates over the Apple Orange Grape Banana
list. The for loop stores each value individually on each iteration, and the echo command prints the value on the terminal.
4. The βforβ Loop in One Line with Files
The for loop with the cp command can copy files to a specific folder, serving the purpose of backing up crucial data. The wildcard (*) helps operate on the specific types of files. Run the below code to back all text files of one directory to another:
for i in /home/susmit/*.txt; do cp "$i" /home/susmit/backup; done
for i in /home/susmit/*.txt;
marks the start of a for loop. It iterates over each file of the /home/susmit/
directory with a .txt
extension and stores each filename on i. And then, the cp command copies the files to the /home/susmit/backup
directory.
5. Filenames in Command Substitution
Command substitution eases programmers’ code writing by containing long commands inside a single variable. First, define a variable that contains a directory path. Then, use this variable inside the iteration list to shorten the command length.
Execute the below lines one after another to print all files of a specific folder whose filename starts with s and ends with .sh:
directory="/home/susmit"
for f in "${directory}"/s*.sh; do echo "$directory contains $f"; done
for f in "${directory}"/s*.sh;
initiates a for loop. It uses a command substitution where the directory will be replaced by the assigned value, and for the wild character (*), it iterates over each file in the specified directory, which starts with βsβ and ends with the β.shβ extension. It saves the filename on the f variable, and the echo command prints the value of f on each iteration.
6. Infinite Bash βforβ Loop in One Line
No initialization of condition or iteration expression initiates an infinite loop. When it is necessary to run a specific command an endless amount of times, an infinite for loop comes to the rescue. Run the below command to execute an infinite Bash for loop in One line:
for (( ; ; )); do echo "Hello from Infinity loop"; sleep 1; done
for (( ; ; ));
defines a for loop without initializing condition or iteration expression, which marks an infinite loop. Then, the echo command prints “Hello from Infinity loop” and waits for 1 second on each iteration.
7. Nested Loop in One Line “for” Loop
A nested loop refers to one loop inside another loop. Here, execute the below command to print the combination of two numbers:
for a in {1..2}; do for b in {1..3}; do echo "a is $a and b is $b"; done; done
It prints all possible combinations of two variables, a and b, where a takes values from 1 to 2 and b takes values from 1 to 3, incorporating two for loops in a nested manner. The echo command of the inner for loop prints a message for each combination, displaying the current values of a and b.
Conclusion
In conclusion, mastering the for loop into a single line offers efficiency and conciseness in Bash scripting. Utilizing the power of concise for loops equips programmers to develop their code, ensuring optimal performance and easier maintenance.
People Also Ask
What is a for-loop header?
A for loop consists of two parts. The first is a header that defines a loop variable and the list of items to iterate over. And the second is, body, which contains commands that are executed once for every iteration.
How do you check if a string is empty in Bash?
To check if a string is empty in bash, use the -z
option with a string name in the if statement condition. The syntax is: -z "$string"
. Here, the -z
option checks if the length of the string is zero, indicating an empty variable. If it returns zero, it means it is an empty variable or string.
What is the structure of for loop in Bash?
The basic structure of a for loop in bash is:
for <variable name> in <a list of items>; do
<commands>;
done
What is the function inside the for loop in bash?
The function inside the for loop in Bash is executing a specific set of code repeatedly. The for loop is an iteration statement, which is the repetition of a specific process.
Which command is used to separate more than one command in the same command line?
The semicolon(;) character is used after each command to run more than one command in the same command line.
Related Articles
- 10 Common Bash βforβ Loop Examples [Basic to Intermediate]
- How to Iterate Through List Using βforβ Loop in Bash
- How to Use Bash βforβ Loop with Variable [12 Examples]
- Bash Increment and Decrement Variable in βforβ Loop
- How to Use Bash Parallel βforβ Loop [7 Examples]
- How to Loop Through Array Using βforβ Loop in Bash
- How to Use Bash βforβ Loop with Range [5 Methods]
- How to Use Bash βforβ Loop with βseqβ Command [10 Examples]
- How to Use “for” Loop in Bash Files [9 Practical Examples]
- Usage of βforβ Loop in Bash Directory [5 Examples]
- How to Use Nested βforβ Loop in Bash [7 Examples]
- How to Create Infinite Loop in Bash [7 Cases]
- How to Use Bash Continue with βforβ Loop [9 Examples]
<< Go Back to For Loop in Bash |Β Loops in Bash | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners