Problem: I'm looking for a way to rename or copy a file without overwriting the destination file, if it exists, and then check the success of the move or copy operation. I'm seeking a method that will work with the BSD versions of mv/cp installed on MacOS/Unix, and also the GNU coreutils versions I have on Linux.
In all versions of mv/cp, I can prevent overwriting the destination file with the
mv -n file1 file2 cp -n file1 file2
Similar questions suggest testing the success of mv and cp using the exit status, which is 0 if successful and >0 if an error occurred. However, for both versions of mv/cp, the exit code is 0 when the destination file already exists and the
-n flag is used.
The only other option I can think of is to also use the
-v flag, and look at the output of the command:
mv -nv file1 file2 cp -nv file1 file2
However, the GNU and BSD versions of mv/cp behave differently when the
-nv flags are used and file2 already exists: the GNU versions of mv/cp return nothing, whereas the BSD versions return
file2 not overwritten.
Our previous method was to check whether the destination file exists first, then do the mv/cp operation. Believe it or not, this caused problems because the destination file would sometimes get created by another process between the time that the check was performed and the mv/cp operation was executed.
Is there a way to accomplish this task that works with both BSD and GNU versions of mv/cp?
Alternatively, is there are way to do this using Python 2? I couldn't find a way to do this using os.rename()