[NTLUG:Discuss] Interesting bash shell scripting

Chris Cox cjcox at acm.org
Wed Mar 11 17:48:09 CDT 2009


On Wed, 2009-03-11 at 17:37 -0500, Daniel Hauck wrote:
> 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.

Useful... but perhaps slow... depends...

With GNU ls, you can always do:

ls -Q 

to quote the file entries.

Then something like:

ls -Q | xargs -n1 unrar x

Might be just what you need.





More information about the Discuss mailing list