Shell scripting 101

Shell scripting 101

on Nov 17, 10 • by Alen Zukich • with 1 Comment

I don’t know why, but every time I go back to some simple shell scripting I can never remember the one liner for loop.  For those who know what I’m talking about, it is the one command you need over and over again when it comes to performing the same thing on a set of ...

Home » General Coding » Shell scripting 101

I don’t know why, but every time I go back to some simple shell scripting I can never remember the one liner for loop.  For those who know what I’m talking about, it is the one command you need over and over again when it comes to performing the same thing on a set of files.  I can never seem to remember the simple syntax and it always leaves me scratching my head.

So I thought I would ask a forum on shell scripting and  was promptly answered with:

for file in `ls`; do rm -rf $file; done

I don’t think they were very friendly.  Although they have the syntax correct, please don’t try this at home.  If you don’t know why, please turn off your computer.  In the end, a simple Google search brought me to this blog with all the details.

So in the end a simple command to create copies for all my .java files to .java.bak:

for i in `find . -name "*.java"`; do cp $i $i.bak; done

Don’t forget, those are executable quotes that you’re using for the find command.  Maybe there’s a better way to do this, but in the end I find the one liner for loop very handy…if only I can remember it.

On another note, I tried this with my Windows Cygwin installation and it doesn’t work.  Anyone with insights into that?

Related Posts

One Response to Shell scripting 101

  1. Alan Rocker says:

    I’d recommend using the $(…..) notation, rather than the backticks, if your shell will support it.

    I.e. for i in $(find . -name “*.java”); do cp $i $i.bak; done

    It’s much easier to see, especially in small print, or when the command involves a lot of quotes.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Scroll to top