What's the reason behind having -n option for mv command?
Sorry for a question that may seem dumb but learning UNIX basics I still can not grasp benefits of using
mv -n source file target file
I can understand the need for
cp -n source file target file
when you get a copy with contents untouched but the former baffles me.
I know that this about preventing from overwriting a target file with contents of a source file (not in opposite order, right?) but why rename at all if you don't want to annihilate the target file? What's the point?
Would be glad to feel enlightened on the subject.
Last edited by scrutinizerix; 02-29-2016 at 01:03 PM..
According to the man page of OS X i found in the net "-n" prevents the mv command to overwrite already existing files. That means: if you have files A, B and C and you do a
mv A D
you will end up with three files again, B, C and D (the former A). Whereas, when you issue:
mv A B
you will end up with only two files: B (the former A) and C. The original B will be wiped out. This may sometimes be the desired result, but sometimes it may not. To guard against accidentally wiping out a file you might want to keep is the reason "-n" exists.
I hope this helps.
The Following User Says Thank You to bakunin For This Useful Post:
Both A and B are untouched so B IS NOT the former A. Right?
Yes. This is what i'd expect.
I'd also expect some diagnostic message to be issued (i don't have OS X but i suppose it would be something along the lines of "Error: cannot ....") and the return-code to be non-zero. This is a common trait of UNIX-commands: whenenver they cannot do what is asked they will return a non-zero error code. Try the following:
ls -l /etc/hosts
echo RC is $?
ls -l /some/nonexisting/file
echo RC is $?
/etc/hosts is a file supposed to exist, so the return code should be zero, the second file does not exist, so the error code will be presumably 2 (if OS X-ls works the same way as my ls on AIX, the value might differ but it should be non-zero in any case).
Below are the screenshots of my actions in OS X Terminal. As you see there're no alert messages. I have cat'ed both files beforehand so that their contents became evident. If I pass -n option then nothing happens - both are kept in the state they used to prior running the command (as evidenced in the portion of their directory listing I invoked through ls -lahG command).