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.
man mv on a GNU system:
do not overwrite an existing file
On a FreeBSD system:
-nDo not overwrite an existing file. (The -n option overrides any
previous -f or -i options.)
if [ ! -e file2 ] && [ ! -L file2 ] then mv file1 file2 # else echo >&2 there is already a file2 file. fi
if ! ls -d file2 > /dev/null 2>&1 then mv file1 file2 fi
Would only run
file2 doesn’t exist. Note that it does not guarantee that a
file2 won’t be overridden because a
file2 could have been created between the test and the
mv, but note that at least current versions of GNU
-n don’t give that guarantee either (though the race condition is narrower there since the check is done within
On the other end, it is portable, allows you to discriminate between the cases, and works regardless of the type of the
file2 file (regular, pipe, even directory).