目錄
描述
cp命令用來完成複製的任務。它可以將系統中的文件或目錄從一個位置複製到另一個位置。
使用示例
複製文件
在最基本的用法裏,cp命令需要兩個參數,源文件和目標文件:
cp <source_file> <destination_file>
此時cp命令將源文件(source_file)複製成一個新文件,並且以destination命名。新文件就像全新的文件一樣,有新的修改時間。
例如,將目錄中的rsa.conf複製到當前目錄下,新的文件名叫做rsa_clone.ini:
$ ll
total 8
drwxr-xr-x 3 root staff 96 2 24 18:13 ./
drwxr-xr-x+ 86 root staff 2752 3 8 18:42 ../
-rw-r--r-- 1 root staff 48 2 24 18:13 rsa.conf
$ cp rsa.conf rsa_clone.ini
$ ll
total 16
drwxr-xr-x 4 root staff 128 3 8 18:42 ./
drwxr-xr-x+ 86 root staff 2752 3 8 18:42 ../
-rw-r--r-- 1 root staff 48 2 24 18:13 rsa.conf
-rw-r--r-- 1 root staff 48 3 8 18:42 rsa_clone.ini
避免覆蓋
如果複製後的新文件名稱在目標目錄中已存在,cp命令會覆蓋掉原來的文件:
$ ll
total 16
drwxr-xr-x 4 root staff 128 3 8 18:42 ./
drwxr-xr-x+ 89 root staff 2848 3 23 21:33 ../
-rw-r--r-- 1 root staff 48 2 24 18:13 rsa.conf
-rw-r--r-- 1 root staff 48 3 8 18:42 rsa_clone.ini
$ cp rsa.conf rsa_clone.ini
$ ll
total 16
drwxr-xr-x 4 root staff 128 3 8 18:42 ./
drwxr-xr-x+ 89 root staff 2848 3 23 21:33 ../
-rw-r--r-- 1 root staff 48 2 24 18:13 rsa.conf
-rw-r--r-- 1 root staff 48 3 23 21:33 rsa_clone.ini
可以看到這種場景下cp命令不會報錯,而是直接將原來的rsa_clone.ini文件覆蓋掉了(最後修改時間發生了變化)。
加上-i選項可以強制shell詢問是否需要覆蓋已有文件。如果不回答y,文件複製過程中斷:
$ cp -i rsa.conf rsa_clone.ini
overwrite rsa_clone.ini? (y/n [n]) n
not overwritten
總結:
使用如下的命令可以強制shell檢查複製文件是否會造成覆蓋已有文件的現象出現:
cp -i <source_file> <target_file>
將文件複製到現有目錄中
使用如下的命令可以將一個文件複製到一個目錄中:
cp <source_file> <source_path>
例如:
$ cp rsa.conf sub
$ ls -l sub/
total 8
-rw-r--r-- 1 root staff 48 3 23 21:57 rsa.conf
新文件就在sub目錄中了,和源文件同名。
查閱cp文檔
使用man cp查閱cp文檔
man cp
遞歸複製目錄
使用 cp -R <目錄名> <新目錄名> 可以遞歸地複製整個目錄的內容。
cp -R <directory/> <new_directory/>
例如將目錄d1複製,新複製後的目錄名爲d2
$ cp -R d1 d2
💡提示:在目錄d2事先並不存在,它是被cp -R命令創建的。在新的目錄d2中,所有文件都有了新的日期。d2目錄現在已經成爲了d1目錄的完整副本。