for loop in bash (bash for loop)

for loop in bash (bash for loop)

for loop in bash is often used to achieve multiple tasks. Following are a couple of examples:
bash for loop to print numbers:
For loop syntax {X..Y} generates number sequence starting from X untill Y.

 

#root@dock ~]# for i in {1..4}
> do
> echo Iteration: $i
> done
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
[root@dock ~]# 
bash for loop that reads file contents line by line and prints them.
You can do operations on file contents by iterating through them.
[root@dock ~]# for fruit in `cat fruits.txt`
> do
> echo Fruit is $fruit
> done
Fruit is Apple
Fruit is Banana
Fruit is Mango
Fruit is Grapes
Fruit is Pine
Fruit is apple
Fruit is Guava

 

Execute a Linux commnd and iterate through results using a bash for loop.

Example: Take the list of files in a directory and rename them by appending date using bash for loop.

[root@electronproton f_names]# ls
file1  file2  file3  file4
for file in `ls | xargs -l`
do 
	mv $file ${file}_`date +%d%m%Y`
done
[root@electronproton f_names]# ls
file1_18042018  file2_18042018  file3_18042018  file4_18042018

Leave a Reply

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