How to decide that mv moves into a directory rather than replacing directory?
mv a b
attempts to move a
into b
if b
is a directory or a symlink to a directory. Otherwise, it will rename (or copy and delete if on different file systems) a
to b
.
To get a consistent result to move a file into a directory, you can do:
mv file dir/
or
mv file dir/.
If dir
doesn't exist, you'll get an error, and it won't rename file
to dir
.
If, on the other hand, you want to do a rename
without having to worry if the destination file exists as a directory or not, with GNU mv, you can do:
mv -T file dest
In that case, file
will not be moved into dest
if dest
is a directory. However, if both file
and dest
are directories and dest
is empty, file
will be renamed to dest
(and the original dest
removed). If both are directories and dest
is non-empty, mv -T
will complain.
Same, if file
and dest
are not directories (and that includes symlinks including symlinks to directories), file
will be renamed to dest
(though you will get a prompt if you don't have write permission to dest
), and the original dest
will be removed. There's a difference with mv file dest
in the case where dest
is a symlink to a directory. With -T
, file
is renamed to dest
, but without -T
, file
is moved into the directory pointed to by dest
.
So to sum up, after mv -T file dest
, either file
will have been renamed to dest
or you'll get an error message (or a prompt). If the command succeeded, the original dest
, if it existed beforehand will have been removed.
This is entirely dependent of if there was already a directory named '/hello2' already in existence or not.
If /hello2 exists AND is a directory, then move will always move /hello to /hello/hello2
If /hello2 does not exist, then move will always rename /hello to /hello2
If /hello2 exists AND is a file, you will get an error, "cannot overwrite non-directory 'hello2' with directory 'hello'.
I tried these
mkdir test1
mv -v test1 test2
output:`test1' -> `test2'
mkdir test1
mv -v test2 test1
output: `test2' -> `test1/test2'
touch test2
output:mv: cannot overwrite non-directory `test2' with directory `test1'
hope this explains everything. -v
is verbose mode.