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]
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
[root@client ~/Desktop/Scripts] cat convertfile.sh
/bin/ls /Documents > /root/Desktop/Scripts/html_file_list
cut -d’.’ -f1 /root/Desktop/Scripts/html_file_list > /root/Desktop/Scripts/index_list
for i in $list
cp -a /Documents/$i.* /Documents/$i.txt
The above script converts all the *.html file in to *.txt file. It is been explained with screen shot herewith.
The shell script file is shown with cat command and the file is shell script is executed with sh command
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.