23

I have a bourne shell script which performs several tasks. One of these tasks is to move some files to certain directory. Today, when I ran the script I got the following message:

mv: will not overwrite just-created <filename> with <sameFilename>

where filename is the original file name with its full path, and sameFilename is exactly the same file and path. I regularly use this script every day and never got this message before.

Right after running the script i re-run it to see if the error persisted, and I was not able to reproduce it again. I am running this script in a Red Hat 5 Enterprise.

Zombo
  • 1
  • 62
  • 391
  • 407
Nacho Mezzadra
  • 886
  • 2
  • 12
  • 14

2 Answers2

20

Here's how to reproduce it:

> mkdir a b c
> touch a/file
> touch b/file
> mv a/file b/file c/
mv: will not overwrite just-created `c/file' with `b/file'

There may be other ways to reproduce this, but it's reasonable to assume above has happened.

That is, your script moved multiple files with the same name into the same target in one single mv command. After executing the above you will notice that a/file was successfully moved (and b/file left as is), so next time you execute it, the problem will most likely go away.

rodion
  • 14,729
  • 3
  • 53
  • 55
  • can also trigger with `install a.txt a.txt b/`. it will copy the file once, then the second time it will cause the error. while `cp a.txt a.txt b/` will fail with a different input validation error, but also after copying the first time. – gcb May 15 '23 at 11:49
10

It happens because two different files with the same name would be moved to the same place with only one command. The -f option won't help for this case, it only applies when there already is a target file that will be overwritten when running the mv command. What occurs is that one of the files (the first encountered) by mv is moved, and it refuse to move the second one (that would overwrite the other file at risk of loosing user data). This behavior also explains that if you have only two files with the same name the warning will disappear the second time you are running the command.

However if you have many files with the same name in your directory tree the warning can stay there for many runs.

If you know what you are doing a way to avoid this warning is adding the option --backup=numbered to mv. The target files won't be overwritten but backup files created whenever collision occurs. If the idea is to remove these it can easily be done afterward using rm *~.

kriss
  • 23,497
  • 17
  • 97
  • 116