How to create a for loop script

Revision as of 21:53, 29 October 2016 by Admin (talk | contribs) (Created page with "<seo ''title''="The best guide on how to save time with for loops!" titlemode="append" ></seo> ==Overview== For loops can work wonders for you once you learn the basics. Ima...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search


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