[NTLUG:Discuss] Interesting bash shell scripting

Daniel Hauck daniel at yacg.com
Wed Mar 11 17:37:44 CDT 2009


Just thought I'd take a moment to share something I learned.

I have this folder with a set of RAR archive files and I wanted to
extract them but they are large and it consumes time to use a GUI.  So I
decided I wanted to use the command line in some way that makes sense.
Unfortunately, I can't just say "unrar x *.rar" because unrar doesn't
like this.

So I thought "use a for loop!"  And I tried this:

for i in `ls -1` ; do unrar x "$i" ; done

But that didn't quite yield what I was after as it did weird things in
the presence of filenames with spaces in them... and yes, these files
have spaces in the names.  So what next?

bash's "read" should be able to read a line into a variable and handle
spaces just fine!  So I did this:

ls -1 | for i in read ; do unrar x "$i" ; done

This also had problems.

Finally I did a little googling and found this:

ls | while read f ; do unrar x "$f" ; done

The while loop worked better than the for loop.  I am unsure why that is
the case exactly but I am sure Chris will be able to offer a better
analysis of the problem and the solutions.  But this technique is rather
useful so I thought I would share.



More information about the Discuss mailing list