[NTLUG:Discuss] Interesting bash shell scripting

Kevin Lee klee24 at gmail.com
Wed Mar 11 18:13:30 CDT 2009


I've run into this many times.  I believe the problem with

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

is your IFS variable. By default IFS is a space and/or newline.  Because the
file had a space in the name, bash interpreted the file name as 2 separate
values.  I suspect that your original script would work as expected if you
did this:

export IFS=$'\n'
for i in `ls -1`;do unrar x "$I"; done

Be careful though, modifying the IFS might have unintended consequences
later on in the script. You may want to save it before the loop and restore
it after the loop, or you could just use Chris' suggestion and use ls -Q =)



On Wed, Mar 11, 2009 at 5:37 PM, Daniel Hauck <daniel at yacg.com> 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.
>
> _______________________________________________
> http://www.ntlug.org/mailman/listinfo/discuss
>


More information about the Discuss mailing list