Paul L. Snyder on 5 Nov 2005 16:41:36 -0000


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] bash script help


Quoting Art Alexion <art.alexion@verizon.net>:

> I have a script that used to work called prepend.filename.  It consists
> of
> 
> #!/bin/bash
> 
> for file in ${2}
> do
> mv -v $file ${1}$file
> done
> 
> 
> I used to be able to run it like this
> 
> prepend.filename Chipmunks- *.mp3
> 
> and it would prepend Chipmunks- to every mp3 file in the current working
> directory.  Now strangely, it works on one file, then exits.  Run it
> again and it works on the next file and exits again.  What went wrong?

What's happening is that the shell is performing filename expansion
before your script is executed.  Thus, if you have the files
'meatloaf.mp3' and 'roadkill.mp3' if your working directory and
execute the command

 % prepend.filename Chipmunks- *.mp3

Bash will actually replace this with

 prepend.filename Chipmunks- meatloaf.mp3 roadkill.mp3

Bash then executes the prepend script.  When it comes to the first line,
it expands $2 into the second command-line argument:

 for file in meatloaf.mp3

If you change ${2} to ${1} in the script and quote your glob argument on
the command-line, it should fix the problem:

 % prepend.filename Chipmunks- '*.mp3'

This will delay expansion of the glob until the 'for' command is
executed in the script.  This means that the script will still work,
even if your mp3 files have spaces in them.  (Otherwise, the shell
performs word splitting...see 'man bash'.)

As a further option, you could change ${2} to ${*}, which will expand
to all of the command-line arguments.  Then you will only need to quote
your glob if any of the filenames have spaces.  This would require a
couple more changes to your script, to move $1 out of the way:

 #!/bin/bash
 PREFIX=${1}
 shift
 for file in ${*}
 do
   mv -v ${file} ${PREFIX}$file
 done

Cheers,
Paul
___________________________________________________________________________
Philadelphia Linux Users Group         --        http://www.phillylinux.org
Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce
General Discussion  --   http://lists.phillylinux.org/mailman/listinfo/plug