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

Re: shell script question

On Sun, Oct 12, 2003 at 06:37:16PM -0400, Jeff Elkins wrote:
> I'm trying to write a script to change spaces in a filename to the
> underscore character:
> #!/bin/sh
> for i in *; do
>         if test -f $i; then
>           mv $i `echo $i | tr '" "' '_'`
>     fi
> done
> When run, it gives me the error "too many args in line four."

If you find yourself writing $variable without double quotes around it
in shell, you should think twice to make sure that you know exactly what
expansion rules are going to apply to it. Usually the answer is "more
than you wanted".

Try this instead (untested):

  #! /bin/sh
  for i in *; do
    if test -f "$i"; then
      mv "$i" "`echo "$i" | tr ' ' _`"

Also consider 'set -e' just below the #! line, in case one of the mv
commands goes bananas for some reason.


Colin Watson                                  [cjwatson@flatline.org.uk]

Reply to: