Sunday 2 February 2020

For loop in bash



  • How do I use bash for loop to repeat certain task under Linux / UNIX operating system? How do I set infinite loops using for statement? How do I use three-parameter for loop control expression?
  • A ‘for loop’ is a bash programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement i.e. it is the repetition of a process within a bash script. For example, you can run UNIX command or task 5 times or read and process list of files using a for loop. A for loop can be used at a shell prompt or within a shell script itself.

or loop syntax
Numeric ranges for syntax is as follows:
for VARIABLE in 1 2 3 4 5 .. N
do
 command1
 command2
 commandN
done
OR
for VARIABLE in file1 file2 file3
do
 command1 on $VARIABLE
 command2
 commandN
done
OR
for OUTPUT in $(Linux-Or-Unix-Command-Here)
do
 command1 on $OUTPUT
 command2 on $OUTPUT
 commandN
done
This type of for loop is characterized by counting. The range is specified by a beginning (#1) and ending number (#5). The for loop executes a sequence of commands for each member in a list of items. A representative example in BASH is as follows to display welcome message 5 times with for loop
#!/bin/bash
for i in 1 2 3 4 5
do
   echo "Welcome $i times"
done

Sometimes you may need to set a step value (allowing one to count by two’s or to count backwards for instance). Latest bash version 3.0+ has inbuilt support for setting up ranges
#!/bin/bash
for i in {1..5}
do
   echo "Welcome $i times"
done
Bash v4.0+ has inbuilt support for setting up a step value using {START..END..INCREMENT} syntax:
#!/bin/bash
echo "Bash version ${BASH_VERSION}..."
for i in {0..10..2}
  do 
     echo "Welcome $i times"
 done
Sample outputs:
Bash version 4.0.33(0)-release...
Welcome 0 times
Welcome 2 times
Welcome 4 times
Welcome 6 times
Welcome 8 times
Welcome 10 times

No comments:

Could not start a new session. Response code 500. Message: Failed to read marionette port

There is bug in firefox binary installed using apt/snap, I faced same issue when I installed firefox from apt package respository. I solved ...