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