The basic syntax of a for loop in Bash is: forvariableinlistdocommandsdone Examples Example 1: Iterating Over a List of Words #!/bin/zshforwordinapple banana cherrydoecho"The word is:$word"done Example 2: Iterating Over a Range of Numbers ...
In the following example, we are iterating through a range of numbers. When the current iterated item is equal to ‘2’, thecontinuestatement will cause execution to return to the beginning of the loop and to continue with the next iteration: fori in{1..5};doif[["$i"=='2']];then...
Caution: As a best practice, you should always quote the bash variables when you are referring it. There are few exceptions to this best practice rule. This is one of them. If you double quote the variable in this for loop, the list of values will be treated as single value. Lot of ...
and most used loop is the “for” loop. So, today we will be looking at the syntax and working of the “for” loop for a series of numbers, i.e., 1 to 10. Let’s start by opening a terminal shell with the help of a “Ctrl+Alt+T” command on the Ubuntu 20.04 desktop system...
The script uses a for loop to iterate over a range of numbers from 1 to 20. The loop variable 'i' represents each number in the range. Within the loop, an if statement checks if the current number ('i') is odd using the condition i % 2 != 0. ...
You may want to run thefor loopNnumber of times, for that, you can use bash built-in sequence generator"{x..y[..incr]}"which will generate a sequence of numbers. X= Starting Integer value Y= Ending Integer value Incr= optional Integer value which does increment of integers ...
Multiple for loop variations are available in bash; we will quickly see some below. for in the Range of Numbers We can specify a list of numbers with a for loop and can iterate on those numbers one by one, as depicted by the following example: for i in 1 3 8 do echo $i done ...
for filename in `ls *.txt` do echo "File No-$n : $filename" ((n++)) done Output: Run the script. $ bash forloop1.sh The following output will appear after running the script. Example-5: For loop to read a range ‘for’ loop can be used for reading range of data. The foll...
Alternatively, loop from ten to zero counting down by even numbers: #!/bin/bash # For loop with reverse range increment numbers for i in {10..0..2} do echo "Element $i" done Execute the script to print every other element from the range in decreasing order. ...
For instance, in the below example, the loop will repeat each item in the list of strings and variable element fixed to the current item. for element in Gold Silver Diamond Platinum do echo "Element: $element" Done Over a Number Range Similarly, to define a range of numbers, one can ...