cp
復制目錄和文件
對于系統管理員來說,在文件系統中將文件和目錄從一個位置復制到另外一個位置是家常便飯,而cp就是可以煮飯的工具之一。
cp需要源對象和目標對象,源對象在前,目標對象在后面。
1. 常用選項
基本用法
[root@local tmp]# ll total 0 -rw-rw-r--. 1 gentoo gentoo 0 Jul 29 09:28 test.txt [root@local tmp]# stat test.txt File: `test.txt' Size: 0 Blocks: 0 IO Block: 4096 regular empty file Device: 802h/2050d Inode: 1310723 Links: 1 Access: (0664/-rw-rw-r--) Uid: ( 500/ gentoo) Gid: ( 500/ gentoo) Access: 2016-07-29 09:29:03.019982074 -0400 Modify: 2016-07-29 09:28:08.737003238 -0400 Change: 2016-07-29 09:28:08.737003238 -0400 [root@local tmp]# cp test.txt / [root@local tmp]# stat test.txt File: `test.txt' Size: 0 Blocks: 0 IO Block: 4096 regular empty file Device: 802h/2050d Inode: 1310723 Links: 1 Access: (0664/-rw-rw-r--) Uid: ( 500/ gentoo) Gid: ( 500/ gentoo) Access: 2016-07-29 09:29:03.019982074 -0400 Modify: 2016-07-29 09:28:08.737003238 -0400 Change: 2016-07-29 09:28:08.737003238 -0400 [root@local tmp]# ll test.txt -rw-rw-r--. 1 gentoo gentoo 0 Jul 29 09:28 test.txt
這是最基本的用法,但是這樣復制有些時候會修改文件或者目錄的相應屬性,不想修改就用接下來的選項
-a 保留原來所以參數進行復制文件或目錄,因為cp不同對象執行時會修所所屬主,所屬組,時間、權限等等屬性,可是有些時候進行對于原文件進行備份是我們不希望修改這些熟悉,所以就需要用-a 選項(常用選項)
root@local tmp]# ll total 0 -rw-rw-r--. 1 gentoo gentoo 0 Jul 29 09:28 test.txt [root@local tmp]# stat test.txt File: `test.txt' Size: 0 Blocks: 0 IO Block: 4096 regular empty file Device: 802h/2050d Inode: 1310723 Links: 1 Access: (0664/-rw-rw-r--) Uid: ( 500/ gentoo) Gid: ( 500/ gentoo) Access: 2016-07-29 09:28:08.737003238 -0400 Modify: 2016-07-29 09:28:08.737003238 -0400 Change: 2016-07-29 09:28:08.737003238 -0400 [root@local tmp]# cp -a test.txt /root/ [root@local tmp]# cd /root [root@local ~]# ll test.txt -rw-rw-r--. 1 gentoo gentoo 0 Jul 29 09:28 test.txt [root@local ~]# stat test.txt File: `test.txt' Size: 0 Blocks: 0 IO Block: 4096 regular empty file Device: 802h/2050d Inode: 786444 Links: 1 Access: (0664/-rw-rw-r--) Uid: ( 500/ gentoo) Gid: ( 500/ gentoo) Access: 2016-07-29 09:28:08.737003238 -0400 Modify: 2016-07-29 09:28:08.737003238 -0400 Change: 2016-07-29 09:29:03.019982074 -0400
通過上面的實驗,我們可以發現出來Change time改變,其他的屬性均為改變。這就是-a選項的目的,不用-a選項都會修改,具體請自行嘗試。
-i 若目標路徑中存在原文件,會詢問我們是否覆蓋它
[root@local tmp]# cp -i /tmp/test.txt / cp: overwrite `/test.txt'? y [root@local tmp]# ll /test.txt -rw-r--r--. 1 root root 0 Jul 29 09:41 /test.txt
-f 強制覆蓋,當我們復制一個文件到目標路徑時,若原文件存在于目標路徑中,我們可以使用-f 強制覆蓋,并且不提醒我們。、
[root@local tmp]# cp -f /tmp/test.txt / [root@local tmp]#
–preserve[=ATTR_LIST] 用這個選項在復制過程選擇時間戳,屬主,權限是否保留
mode: 權限 ownership: 屬主屬組 timestamp: links xattr context all
-p: 等同–preserv=mode,ownership,timestamp
-u:僅僅當目標文件的內容比原文件新才進行復制
-R, -r, –recursive :復制當前目錄及目錄下面的文件一起
2.注意
SRC是文件:
如果目標不存在:新建DEST,并將SRC中內容填充至DEST中
如果目標存在:
1.DEST是文件:將SRC中的內容覆蓋至DEST中基于安全,建議為cp命令使用-i選項
2.DEST是目錄:在DEST下新建與原文件同名的文件,并將SRC中內容填充至新文件中
復制文件和目錄cp
cp SRC… DEST
SRC…:多個文件
DEST必須存在,且為目錄,其它情形均會出錯;
cp SRC DEST
SRC是目錄:此時使用選項: -r 如果DEST不存在:則創建指定目錄,復制SRC目錄中所
有文件至DEST中;
如果DEST存在: 1. DEST是文件:報錯 2.DEST是目錄:
原創文章,作者:fighter,如若轉載,請注明出處:http://www.www58058.com/26932