For loop syntax with examples in Linux / Unix

For loop syntax with examples in Linux / Unix

A loop contains list of codes that communicate with the list of commands and execute it until the loop condition is true. For loop is one of the necessary thing to do repetitive task in shell scripting. Previously we have seen about IF condition syntax with examples in Linux / Unix.

Syntax of for loop:

for arg in [list]
do
command1
command2
….
done

Example:

Consider a scenario that their is a total of 10 .html file in a folder. I need to convert all the 10 .html file in to .txt file using shell script. Lets accomplish this task using for loop.

First Create 10 index.html file in a folder
mkdir /Documents ; cd /Documents ; touch  index1.html index2.html index3.html index4.html index5.html index6.html index7.html index8.html index9.html index10.html

cd /root/Desktop/Scripts/

For loop syntax with examples in Linux / Unix

[root@client ~/Desktop/Scripts] cat convertfile.sh
#!/bin/bash
cd /Documents
/bin/ls /Documents > /root/Desktop/Scripts/html_file_list
cut -d’.’ -f1 /root/Desktop/Scripts/html_file_list > /root/Desktop/Scripts/index_list
list=`cat /root/Desktop/Scripts/index_list`
for i in $list
do
cp -a /Documents/$i.* /Documents/$i.txt
done
The above script converts all the *.html file in to *.txt file. It is been explained with screen shot herewith.

For loop syntax with examples in Linux / Unix

The shell script file is shown with cat command and the file is shell script is executed with sh command

For loop syntax with examples in Linux / Unix

After the script is completed all the *.html files are copied and converted in to  *.txt files.

To find more about how the script works in each and every step use “sh -x <filename>”. It will describe you the script flow by each and every steps.

For loop syntax with examples in Linux / Unix

For loop syntax with examples in Linux / Unix




2 thoughts on “For loop syntax with examples in Linux / Unix

  1. ashwin

    You concentrated only on one type for loop in bash. There is also other type like this:
    for ((i=0;i<10;i++))
    do
    echo $i
    done
    which i find very useful when scripting with loops.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *