本文永久更新連結位址:http://www.linuxidc.com/Linux/2016-03/129304.htm
Copy Files And Directory
檔案的複制和移動對于大多數計算機愛好者來說是耳熟能詳的,在windows下直接滑鼠右鍵複制粘貼,重命名等等,看着是那麼簡單,但是步驟也不少,但是在Linux中檔案的複制與移動也僅僅就是一句指令就可以實作,下面我們就來看看檔案中的複制指令把..
Name:
cp(copy files and directory)複制檔案和目錄
指令格式:
cp [選項]... SOURCE... DESC
"..."表示源檔案可以有多個是以我們可以從上面得到這樣的結論:
cp隻能把一個檔案複制成另一個檔案
cp可以把多個檔案複制到一個目錄裡
3.如果cp後面有很多檔案,那麼最後一個一定是一個目錄
下面我們通過代碼詳細了解一下cp的實際用法:
[[email protected] ~]$ cp /etc/man_db.conf /tmp/test
[[email protected] ~]$ ls /tmp/
anaconda.log storage.log
hsperfdata_root systemd-private-3E1wlM
ifcfg.log systemd-private-cxUWsv
ks-script-5GePg3 systemd-private-StjRUY
packaging.log test
program.log vmware-root
ssh-x1RDJKuGNlHn yum.log
[[email protected] ~]$
這句指令是把man_db.conf複制到/tmp/下面并且把檔案改名為test
如果目标目錄下存在目标檔案,那麼源檔案的内容就會覆寫目标檔案
[[email protected] tmp]$ cp /etc/man_db.conf /tmp/test
[[email protected] tmp]$ cp /etc/locale.conf /tmp/test
cp:是否覆寫"/tmp/test"?
這樣是不是很清楚明白呢?大家注意這裡cp的互動是因為在alias中定義了一個alias cp='cp -i'的原因,i是cp的一個選項,實作人機互動的作用,這裡的覆寫其實相當于把原來的test檔案删除,然後把源檔案複制到/tmp/下并且改名為test,這一點我們要了解
可是,如果test在/tmp/下是一個目呢?
[[email protected] tmp]$ cp /etc/man_db.conf /tmp/test
[[email protected] tmp]$ ls /tmp/test
man_db.conf
[[email protected] tmp]$
這樣一看就明白了,把源檔案複制到test目錄下,源檔案的名稱不變
下面我們看這樣一段代碼
[[email protected] tmp]$ cp /etc/init.d/ /tmp/
cp: 略過目錄"/etc/init.d/"
[[email protected] tmp]$
這是什麼意思呢,原因很簡單,cp預設機制是複制檔案的,不會複制目錄,可是我們想複制目錄改如何實作呢?
-r:[遞歸選項]複制一個目錄及其目錄下的所有檔案
[[email protected] tmp]$ cp -r /etc/init.d/ /tmp/home
[[email protected] tmp]$ ls /tmp/home
functions netconsole network README
[[email protected] tmp]$
這樣大家是不是看明白了呢? -r會把一個目錄以及目錄下的所有的檔案遞歸複制出來到目标目錄中,大家仔細看,/tmp下是沒有home目錄的,這樣的執行會直接建立一個home目錄并且home目錄裡面有源目錄的内容,大家了解了嗎
我們假如home是一個檔案,看一看什麼情況
[[email protected] tmp]$ cp -r /etc/init.d/ /tmp/1
cp: 無法以目錄"/etc/init.d/" 來覆寫非目錄"/tmp/1"
[[email protected] tmp]$
會提示你cp: 無法以目錄"/etc/init.d/" 來覆寫非目錄"/tmp/1",但是在有些系統的版本中是可以執行的,執行的結果就是會覆寫檔案的内容,并且建立成一個沒有源檔案的錯誤的連結,好這裡大家注意一下就可以了
下面我們看一下cp的一些其它選項
-f:表示強行複制
如果目标檔案存在,不進行人機互動,直接覆寫檔案内容,是不是很霸道呢?
[[email protected] tmp]$ cp -f /etc/man_db.conf /tmp/1
[[email protected] tmp]$
-i:進行人際互動,前面我們講過了
-p:保留檔案的屬主,屬組,時間戳
1234 [[email protected] tmp]$ cp -p ./storage.log ./storage.log1
[[email protected] tmp]$ ll
-rw-r--r--. 1 root root 0 3月 9 23:36 storage.log
-rw-r--r--. 1 linuxidc jason 0 3月 9 23:36 storage.log1
-L:複制的是連結,實際上複制的是連結指向的檔案(預設的是-L)
[[email protected] etc]$ ll
lrwxrwxrwx. 1 root root 13 3月 10 07:19 rc.local -> rc.d/rc.local
[[email protected] etc]$ cp -L /etc/rc.local /tmp/
[[email protected] etc]$ ll /tmp
-rw-r--r--. 1 linuxidc jason 473 3月 10 16:59 rc.local
看明白是什麼意思了麼?複制過來後顯示的是一個檔案,檔案的内容是rc.d/rc.local的内容,而不是連結
-P:保持連結自身
[[email protected] etc]$ cp -P /etc/rc.local /tmp/rc12.local
[[email protected] etc]ll /tmp
lrwxrwxrwx. 1 linuxidc jason 13 3月 10 17:04 rc12.local -> rc.d/rc.local
原來的是連結,複制過來的還是連結
-d:與-P一樣,複制連結自身
-R:與-r一樣,遞歸
-a:same as -dR,猜猜什麼意思j_0006.gif,"歸檔",就是不改變檔案的所有屬性,備份存放
好了,示範到這,cp這個指令我想你一定會是熟記于心了,在回頭鞏固鞏固。
本文永久更新連結位址:http://www.linuxidc.com/Linux/2016-03/129304.htm