Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using "mv" command for moving and renaming, script sees it as a directory instead of new filename

Tags:

linux

shell

unix

I have a question regarding the mv command.

In order to move and rename the file, I did mv file someDir/File2 in my terminal and it moved file into someDir with new name called File2.

However, when I do it with shell script, it sees the File2 part as a directory, instead of the new name for the file.

So I have two variables, NEWDir=newDir, NEWF=newName

for i in *.txt ; do
  mv $i $NEWDIR/$NEWF
done

I run this script, it says the following:

mv: target 'newName' is not a directory.
like image 445
Spencer Ovetsky Avatar asked Nov 29 '25 06:11

Spencer Ovetsky


1 Answers

mv requires the destination to be a directory only if more than one source argument is given.

In this case, that can be caused by your variables being split due to lack of quoting. Use double quotes -- as http://shellcheck.net/ directs -- around all expansions.

for i in *.txt ; do
  mv "$i" "$NEWDIR/$NEWF"
done

Note that only the last file iterated over will actually be left behind with the given name -- the rest will be overwritten by their successors.

like image 59
Charles Duffy Avatar answered Nov 30 '25 21:11

Charles Duffy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!