推荐:每天学一个Linux命令(17):chmod命令介绍mv命令用于移动和重命名文件和目录。或者将文件从一个目录移动到另一个目录。如果将文件移动到现有目标文件,则目标文件的内容将被该文件的内容覆盖。如果源是文件而目标是目录,mv将移动文件。如果source是目录,target只能是目录(不能是文件),mv会重命名目录。使用mv命令移动文件时,如果target不同,会出现以下4种不同的结果:如果target是指定的特定路径,则源文件会被移动到该目录下,文件名不会改变。如果目标不是目录,则源文件名(只能有一个)将成为目标文件名,如果存在同名文件,则覆盖已存在的同名文件。如果源文件和目标文件在同一个目录下,mv的作用就是修改文件名。当目标为目录时,可以有多个源文件或目录,所有源文件都会移动到目标目录下。并且所有文件都将保留以前的文件名。语法格式mv[option]sourcefileordirectorytargetfileordirectorymv[options]sourcedestinationoptiondescription-b#当文件存在时,在覆盖前为其创建备份-f#如果移动到的文件或目录相同作为目标重复,直接覆盖-i#交互操作,覆盖前会提示用户确认操作,用户可以输入Y/N确认是否覆盖-u#如果目标文件已经存在且具有相同name为要移动的文件,只有在源文件比目标文件新时,才会更新目标文件-t#指定mv的目标目录。此选项用于将多个文件移动到一个目录。此时目标文件在前,源文件在后。-S:#为备份文件指定一个后缀,而不是使用默认的后缀(去除源文件中的斜线“/”)-n#不覆盖任何现有文件-T#将目标视为普通文件文件,而不是目录-v#详细输出命令执行过程应用示例#将文件移动到目标目录[root@centos7testdir]#lltotal0-rw-r--r--1rootroot0Feb252021filetest-rw-r--r--1rootroot0Feb252021testfile[root@centos7~]#mvmingongge.txttestdir/[root@centos7~]#lltestdir/total0-rw-r--r--1rootroot0Feb252021filetest-rw-r--r--1rootroot0Jan208:43mingongge.txt-rw-r--r--1rootroot0Feb252021testfile#Moveandrecommandfile[root@centos7testdir]#mvmingongge.txttest/mingongge[root@centos7testdir]#lltest/total0-rw-r--r--1rootroot0Jan208:50mingongge如果有目标位置的同名文件,我们不希望它被覆盖,我们可以添加-n选项。[root@centos7testdir]#ll*.txtdir/*.txt-rw-r--r--1rootroot0Jan208:58dir/test1.txt-rw-r--r--1rootroot0Jan208:58dir/test2.txt-rw-r--r--1rootroot0Jan209:03test1.txt-rw-r--r--1rootroot0Jan208:57test2.txt-rw-r--r--1rootroot0Jan209:03test3.txt[root@centos7testdir]#mv-nv*.txtdir/'test3.txt'->'dir/test3.txt'#目标目录下没有test3.txt文件,所以移动成功[root@centos7testdir]#lltotal0drwxr-xr-x2rootroot57Jan209:04dir-rw-r--r--1rootroot0Jan209:03test1.txt-rw-r--r--1rootroot0Jan208:57test2.txt备份函数#如果test2.txt存在,则重新排序作为测试2。txt,会备份原文件[root@centos7dir]#cattest1.txt1[root@centos7dir]#cattest2.txt2[root@centos7dir]#mv-btest1.txttest2.txtmv:覆盖“test2.txt”?y[root@centos7dir]#lltotal12-rw-r--r--1rootroot2Jan209:12test2.txt-rw-r--r--1rootroot2Jan209:12test2.txt~-rw-r--r--1rootroot2Jan209:12test3.txt[root@centos7dir]#cattest2.txt1[root@centos7dir]#cattest2.txt~2#如果test3.txt存在,会重新排序为test3.txt.bak[root@centos7dir]#mv-b--suffix=.baktest2.txttest3.txtmv:覆盖'test3.txt'?y[root@centos7dir]#lltotal12-rw-r--r--1rootroot2Jan209:12test2.txt~-rw-r--r--1rootroot2Jan209:12test3.txt-rw-r--r--1rootroot2Jan209:12test3.txt.bak[root@centos7dir]#cattest3.txt1[root@centos7dir]#cattest3.txt.bak3每天学一个Linux命令(16):mkdir每天学一个Linux命令(15):man每天学一个Linux命令(14):cat