Linux cli cp

最後更新: 2017-04-12






-u, --update

copy only when the SOURCE file is newer than the destination



same as "--preserve=mode,ownership,timestamps"


-l, --link

hard link files instead of copying (ls -il * 是一樣)

-s, --symbolic-link

make symbolic links instead of copying


follow command-line symbolic links in SOURCE

-L, --dereference      

always follow symbolic links in SOURCE

-H 與 -L 分別

Without the -R switch, the behavior of cp -H and cp -L is identical.

The -H option to cp modifies the behavior of -R (recursive copy) as follows:

With the -R switch, cp -H only dereferences symbolic links that occur in the cp command itself,
while -L also dereferences symbolic links inside the recursively copied directories.

cp -R -H source/ dest/

If source is a symlink to a directory, cp will dereference the symlink,
if cp encounters any symlinks in source's subdirectories,
it will create symlinks in the destination folder.

cp -R -L source/ dest/

behaves similarly, it will also dereference symlinks in source's subdirectories
(copy the files those symlinks point to)


-b / --backup[=CONTROL]

make a backup of each existing destination file

-a, --archive

same as -dR

-d     same as --no-dereference --preserve=links

-R, -r, --recursive


"-r" 在有些情況都有用, 例如

# 由 ext4 copy file 到 exfat

cp -a user01 /mnt/recovery_disk

cp: failed to preserve ownership for 'File-Path': Operation not permitted

# 這樣就無事

cp -r user01 /mnt/recovery_disk


cp --parents ./test/a/testfile ./backup



# perform a lightweight copy, where the data blocks are copied only when modified.


cp --reflink=always


install - copy files and set attributes


-b                                          # make a backup of each existing destination file

-g, --group=GROUP

-o, --owner=OWNER

-m, --mode=MODE


hardlinks 與 reflinks


FS 內的 inode, reflink 與 data 結構

name1 -- hardlink --> inode1 -- reflink ---> data
name3 -- hardlink -/                      /
name4 -- hardlink --> inode2 ---reflink -/


cp --link name1 name3

A hard link is merely an additional name for an existing file

Since hardlinks reference inodes directly

 - they're restricted to the same file system

 - they cannot be created for directories

Note a file can be held open by a process while all hardlinks are subsequently unlinked,

leaving the data accessible until the file is closed.

The main use for multiply hardlinked files is to create efficient backups.(當有不同時 Delete + Create)


cp --reflink name1 name4

reflinks are supported by BTRFS and OCFS2 and support transparent copy on write which is especially useful for snapshotting.

Note that since separate inodes are used, one can have different permissions to access the same data.

Reflinks have the same use as hardlinks, but are more space efficient and

generally handle all subsequent operations on a file, not just unlink().