简介

mv(英文全拼:move file)命令可以移动文件或对其改名、或将文件或目录移入其它位置。

命令格式

mv [OPTION]… [-T] SOURCE DEST mv [OPTION]… SOURCE… DIRECTORY

mv [OPTION]… -t DIRECTORY SOURCE…

常用参数

-i 若存在同名文件,则向用户询问是否覆盖
-f 在mv操作要覆盖某已有的目标文件时不给任何指示
-b 当目标文件或目录存在时,在执行覆盖前,会为其创建一个备份
-u 当源文件比目标文件新,或者目标文件不存在时,才执行移动此操作
-n 不要覆盖任何已存在的文件或目录

四种情况说明

mv source_file(文件) dest_file(文件) 将源文件名 source_file 改为目标文件名 dest_file
mv source_file(文件) dest_directory(目录) 目录名 dest_directory 已存在,将文件 source_file 移动到目标目录 dest_directory 中
目录名 dest_directory 不存在则 ,抛出一个错误
mv source_directory(目录) dest_directory(目录) 目录名 dest_directory 已存在,将 source_directory 移动到目录名 dest_directory 中;
目录名 dest_directory 不存在则 source_directory 改名为目录名 dest_directory
mv source_directory(目录) dest_file(文件) 出错
  1. [root@localhost ~]# echo aaa > file_a.txt
  2. [root@localhost ~]# echo bbb > file_b.txt
  3. [root@localhost ~]# echo ccc > file_c.txt
  4. [root@localhost ~]# head -v file_*.txt
  5. ==> file_a.txt <==
  6. aaa
  7. ==> file_b.txt <==
  8. bbb
  9. ==> file_c.txt <==
  10. ccc
  11. ## mv 文件到文件
  12. [root@localhost ~]# mv file_a.txt file_d.txt ## 复制到一个不存在的文件
  13. [root@localhost ~]# cat file_d.txt
  14. aaa
  15. [root@localhost ~]# alias mv ## 设置了一个别名,覆盖重名文件时,则提示是否覆盖
  16. alias mv='mv -i'
  17. [root@localhost ~]# mv file_d.txt file_b.txt ## 覆盖到一个已经存在的文件,则提示是因为设置了别名,
  18. mv: overwrite file_b.txt’? y
  19. [root@localhost ~]# cat file_b.txt
  20. aaa
  21. ## mv 文件到目录
  22. [root@localhost ~]# mkdir test
  23. [root@localhost ~]# mv file_b.txt test2/ ## 移动到一个不存在的目录
  24. mv: cannot move file_b.txt to test2/’: Not a directory
  25. [root@localhost ~]# mv file_b.txt test ## 移动到一个存在的目录
  26. [root@localhost ~]# tree test
  27. test
  28. └── file_b.txt
  29. 0 directories, 1 file
  30. ## mv 移动目录到目录
  31. 目录名 dest_directory 已存在,将 source_directory 移动到目录名 dest_directory 中;
  32. 目录名 dest_directory 不存在则 source_directory 改名为目录名 dest_directory
  33. ## mv 移动目录到文件
  34. [root@localhost ~]# mv test file_c.txt
  35. mv: overwrite file_c.txt’? y
  36. mv: cannot overwrite non-directory file_c.txt with directory test

示例

  1. ## -b 当目标文件或目录存在时,在执行覆盖前,会为其创建一个备份
  2. [root@localhost ~]# echo aaa > filea.txt
  3. [root@localhost ~]# echo bbb > fileb.txt
  4. [root@localhost ~]# ll
  5. total 8
  6. -rw-r--r--. 1 root root 4 May 17 17:13 filea.txt
  7. -rw-r--r--. 1 root root 4 May 17 17:13 fileb.txt
  8. [root@localhost ~]# mv -b filea.txt fileb.txt
  9. mv: overwrite fileb.txt’? y
  10. [root@localhost ~]# ll
  11. total 8
  12. -rw-r--r--. 1 root root 4 May 17 17:13 fileb.txt
  13. -rw-r--r--. 1 root root 4 May 17 17:13 fileb.txt~
  14. [root@localhost ~]# cat fileb.txt ## 已经被 filea.txt 覆盖
  15. aaa
  16. [root@localhost ~]# cat fileb.txt~ ## 保留了一个备份文件
  17. bbb