The for loop in a unix/linux shell is used to execute the same thing over and over again, or iteratively. Here are a few examples of simple for loop usage.
The following loop goes through all files names *.jpg and runs the command ‘identify’ for each one of them to determine image pixel sizes.
From the command line, use semi-colons to separate each statement.
# for i in *.jpg; do identify $i; done
The same for loop in a shell script would look like this:
#!/bin/bash for i in *.jpg do identify $i done
The output of either of the above loops would be something like:
file1.jpg JPEG 350×571 350×571+0+0 8-bit DirectClass 24.4KB 0.000u 0:00.010
file2.jpg JPEG 107×140 107×140+0+0 8-bit DirectClass 5.41KB 0.000u 0:00.009
file3.jpg JPEG 700×467 700×467+0+0 8-bit DirectClass 42.4KB 0.000u 0:00.000
file4.jpg JPEG 700×467 700×467+0+0 8-bit DirectClass 40.3KB 0.000u 0:00.000
… and so on until all *.jpg files in the directory were processed.
Another use might be to rename many files in a directory with an “_old”. This method requires getting each file name in the directory ($file), then using ‘sed’ to create a new variable that replaces “.jpg” with _old.jpg” in the filename, then finally moves each file to the new filename.
# for i in *.jpg; do newfile=`echo $i| sed 's/.jpg/_old.jpg/g'`; mv $i $newfile; done
or the same in a bash shell script:
#!/bin/bash for i in *.jpg do newfile=`echo $i | sed 's/.jpg/_old.jpg'` mv $i $newfile done
Instead of using a wildcard, you can use a list, as follows:
for i in red green blue yellow orange do echo $i done
Which, when executed outputs:
The last way that I’ll show is using three expressions to loop through an inequality and incrementing after each loop, as follows:
for (( i=1; i<=5; i++ )) do echo "Variable i equals: $i" done
Which, when executed out puts the following:
Variable i equals: 1
Variable i equals: 2
Variable i equals: 3
Variable i equals: 4
Variable i equals: 5
I hope you found this useful. Leave a comment!