This guide demonstrates one-line for loops in Bash.
Bash for loop
The bash features multiple loop types – for, while, and until. Each type of loop comes with a different structure. However, the fundamentals remain the same. For beginners, this guide explains in-depth about various bash loops and how to implement them.
As the title of this guide suggests, our focus will be on the loop. While for loop generally requires multiple lines, we can represent it in a single line if the loop is simple enough. This process, however, requires an understanding of the fundamentals of bash for a loop.
To run our bash codes, we need a shell script. I already have a dummy script to run our codes.
For loop structure
This is the basic structure of the bash for loop.
do
done
Here’s a quick for loop example implementing this structure.
do
echo "number: $i"
done
Bash also supports C-style for loop. If you have programming background in C, then C-style for loop will be easy to understand.
do
done
Let’s put the C-style for loop in action.
echo "number: $i"
done
For loop can also work with files. In the following example, the loop will search all the partitions under the disk “/dev/sda” and print all of it.
echo "$i"
done
One line for loop
With the basics covered, we can now compress for loops into a single line. Basically, we’ll eliminate the newlines from the entire for loop code. We can also run these loops directly from the command line.
Let’s compress the first example. If we eliminate all the new lines, the code will look like this.
As you can see, all the new lines are removed. Instead, those newlines are replaced with semicolons (;).
We can do the same with C-style for loops.
Have a look at the following example. All the configuration files inside “/etc.” will be copied as a backup to the “~/backup” directory.
For loop with conditionals
In many cases, a loop will contain conditionals to make decisions at various points of the repetition.
Here, the following for loop will print all the even numbers within a fixed range.
if [ $((i%2)) -eq 0 ]; then
echo "$i even"
fi
done
It’s possible to express this entire loop into a single line. Just like before, replace all the newline with semicolons (;).
It’s recommended to write down the loop with proper spacing first. Once the loop is confirmed to work properly, we can safely compress it into a single line.
Miscellaneous examples
Here’s a handful of one line for loops for reference.
The next example will be of an infinite loop.
Final thought
This guide demonstrates various effective one-line for loop examples. It’s very easy to transform a normal for loop into one line. Hopefully, after practicing these examples, readers will have a good idea of using bash for loop in one line.
Happy computing!
from Linux Hint https://ift.tt/2WjpEGV
0 Comments