views:

59

answers:

2

I wrote a small shell script based on an example I found here: https://bbs.archlinux.org/viewtopic.php?id=36305

it takes this:

bash-3.2$ ls
test 001  test 002  test 003  test 004

and turns it into:

bash-3.2$ ls
001  002  003  004  rename.sh

However it gives me this error (even though it works):

bash-3.2$ ./rename.sh
mv: missing destination file operand after `rename.sh'
Try `mv --help' for more information.
`test 001' -> `001'
`test 002' -> `002'
`test 003' -> `003'
`test 004' -> `004'

Though it works correctly, it would be nice to see where I messed up, I assumed by default it would put the files in the same directory (this is the desired output).

#!/bin/bash
ls | while read -r FILE
do
        mv -v "$FILE" `echo $FILE | awk -F ' ' '{print $2}'`
done

Thanks in advance for helping me correct my incorrect code.

A: 

Postman almost has it. For rename.sh, the awk command returns nothing so in effect you have the following command the shell attempts to execute:

mv rename.sh

hence the error message "missing destination file"

you can fix this by testing for the filename of the script, either hardcoded or $0, and executing the mv command only if $FILE does equal the script name.

ennuikiller
and a fix is to only do files that include a space: `ls *' '* | `...
ysth
Thank you this makes so much sense now!
eddylol
Sorry I went of on a tangent, so deleted my answer :)
PostMan
+1  A: 

why are you using ls with an extra process to while loop? Just use a for loop with shell expansion. This is preferred way

#!/bin/bash
shopt -s nullglob
for file in *
do
  if [ -f "$file" ];then
    newfile="${file##* }"
    mv "$file" $newfile"
  fi
done
ghostdog74