How to create a for loop script

From wiki.mikejung.biz
Jump to: navigation, search

Overview

For loops can work wonders for you once you learn the basics. Imagine you have to modify a bunch of files on a webserver, and you would rather not update each file name one at a time. You can use a for loop to save you tons of time! Remember that you should always use the "echo" command to test your script before you put in the real command (like rm -f). If you use echo first and you notice that you made a typo, you can simply modify the loop and try again, without destroying the wrong files.

The first part of a basic for loop (at least in this example) is to find some files somewhere and create a list of those files. We are going to do something with those files of course, but creating a list and checking it twice can save you from a lot of headache and sadness.

find $/location/of/files -n '$file_name*' > $somelist

Now that we have a list of files we can do stuff to them! I like to use cat while will output the list then do something to the files.

for each in `cat $somelist` ; do something $each ; done