Shell – How to Move File Only if Destination Does Not Exist

filesmvshell

Can I use mv file1 file2 in a way that it only moves file1 to file2 if file2 doesn't exist?

I've tried

yes n | mv -i file1 file2

(this lets mv ask if file2 should be overridden and automatically answer no) but besides abusing -i it also doesn't give me nice error codes (always 141 instead of 0 if moved and something else if not moved)

Best Answer

mv -vn file1 file2. This command will do what you want. You can skip -v if you want.

-v makes it verbose - mv will tell you that it moved file if it moves it(useful, since there is possibility that file will not be moved)

-n moves only if file2 does not exist.

Please note however, that this is not POSIX as mentioned by ThomasDickey.

Related Question