Linux mv 命令

2017-12-26|Categories: External cmd|

mv命令的本质

文件移动和重命名的本质是先复制再删除

It first uses some of the same code that's used by cp -a to copy the requested directories and files, then (assuming the copy succeeded) it removes the originals

from info coreutils 'mv invocation'

所以,即使在/tmp这种所有人都拥有写入权限的目录,普通用户也不能更改属于他人的文件名称,因为改名实质上是先复制再删除,而/tmp设置了sticky bit,不允许随意删除他人文件。

报错:inter-device move failed

$ mv -f /app/testdir/ /tmp/trash
mv: inter-device move failed: ‘/app/testdir/’ to ‘/tmp/trash/testdir’; unable to remove target: Directory not empty

原因如下:

mv is actually rename under the cover.

If you move a file to another file, mv assumes you know what you are doing and overwrite the destination file.

If you move a directory to another directory, mv assumes you want to keep the basename of your original directory and create it on the target directory. If there is not yet a directory with that name on the destination side, or if a directory with that name exists but is empty, the operation succeeds.

However, if the target directory already exists and is not empty, this is no more a rename but that should be a recursive file and directory removal. rename isn't designed to do it so it fails, mv doesn't go further as it assumes you didn't want to do it and fails too.

from https://unix.stackexchange.com/a/272206/165450

翻译:

mv实际上是调用rename()系统函数。

如果您将文件移动到另一个文件,mv会假定您知道您正在做什么并覆盖目标文件。

如果将目录移动到另一个目录,则mv会假定您要保留原始目录的基本名称(basename),并将其创建在目标目录中。如果目标端还没有具有该名称的目录,或者该名称的目录存在但是为空,则操作成功。

但是,如果目标目录已经存在并且不是空的,这不再是一个rename(),而应该是一个递归的文件和目录删除。rename()不是为了这么做而设计的,因为它假设你不想这么做,所以它不会继续下去。

解决方法:先cprm

cp -a /app/testdir /tmp/trash/ \
    && /bin/rm -rf /app/testdir/

Leave A Comment