Linux 命令 mv
mv 命令
--no-target-directory 参数确保对目录进行重命名而不是移动
https://www.gnu.org/software/coreutils/manual/html_node/Target-directory.html#Target-directory
‘--no-target-directory’
Do not treat the last operand specially when it is a directory or a symbolic link to a directory. This can help avoid race conditions in programs that operate in a shared area. For example, when the command ‘mv /tmp/source /tmp/dest’ succeeds, there is no guarantee that /tmp/source was renamed to /tmp/dest: it could have been renamed to /tmp/dest/source instead, if some other process created /tmp/dest as a directory. However, if mv -T /tmp/source /tmp/dest succeeds, there is no question that /tmp/source was renamed to /tmp/dest.
In the opposite situation, where you want the last operand to be treated as a directory and want a diagnostic otherwise, you can use the --target-directory (-t) option.
# 将 source 目录重命名为 dest ,如果 dest 存在,则将 source 放到 dest 目录下。
[root@localhost ~]# mv source dest
# 将 source 目录重命名为 dest ,如果 dest 存在,则提示是否覆盖。
[root@localhost ~]# mv -T source dest
mv: overwrite ‘dest’? y
mv: cannot move ‘source’ to ‘dest’: File exists
场景 通配符匹配文件或目录
通配符:
* 匹配任意个字符
? 匹配单个任意字符
格式
<dir>/* 移动指定目录下所有源到目标目录
<dir>/*xxx 后缀
<dir>/xxx* 前缀
<dir>/*xxx* 包含
<dir>/?.xxx 名称为单个字符的 xxx 文件
实战
# 全匹配
[root@localhost ~]# mv test/* dev
# 后缀匹配
[root@localhost ~]# mv dev/*.txt test/
# 前缀匹配
[root@localhost ~]# mv jie* dev
# 包含匹配
[root@localhost ~]# mv *ea* dev
# 将匹配如 a.txt 不会匹配 ab.txt 。? 不是可选,而是表示任意单个字符
[root@localhost ~]# mv test/a?.txt dev
[root@localhost ~]# mv *a??.txt dev
# 可以指定带通配符的多个源
[root@localhost ~]# mv dev/* test/* ./
bugs
# 提示没有找到文件或目录,当指定多个源时,其他存在的源会正常执行。注意这仅仅只是提示。
mv: cannot stat ‘dev/*’: No such file or directory # 这只是提示
[root@localhost ~]# mv dev/* test/* ./
mv: cannot stat ‘dev/*’: No such file or directory 提示 dev/* 没有匹配到任何文件或目录
mv: cannot stat ‘test/*’: No such file or directory 提示 test/* 没有匹配到任何文件或目录
[root@localhost ~]# ll dev
total 0
[root@localhost ~]# ll test
total 0
场景 移动多个文件或目录到指定目录
格式
mv [OPTION]... SOURCE... DIRECTORY
实战
最后一个参数为目标,当移动多个文件或目录到指定目录时,最后一个参数必须是已存在的目录。
[root@localhost ~]# mv a/c.txt a.txt b.txt bak
场景 重命名文件或目录
格式
mv [OPTION]... [-T] SOURCE DEST
实战
# 重命名文件
[root@localhost test]# ll
total 0
-rw-r--r--. 1 root root 0 Aug 2 09:53 a.txt
[root@localhost test]# mv a.txt b.txt
[root@localhost test]# ll
total 0
-rw-r--r--. 1 root root 0 Aug 2 09:53 b.txt
# 重命名目录
[root@localhost test]# ll
total 0
drwxr-xr-x. 2 root root 6 Aug 2 09:55 dev
[root@localhost test]# mv dev pro
[root@localhost test]# ll
total 0
drwxr-xr-x. 2 root root 6 Aug 2 09:55 pro