본문 바로가기
Linux/명령어

[Linux] rsync 명령어 사용법

by A6K 2022. 5. 16.

rsync는 'Remote Sync'의 줄임말로 파일과 디렉토리를 동기화하기 위한 프로토콜이자 리눅스의 유틸리티 명령어다. rsync 명령어를 이용해 로컬에 있는 파일이나 디렉토리를 원격 호스트로 보내거나 원격에 있는 파일, 디렉토리를 로컬로 복사해 올 수 있다.

rsync 명령은 데이터 전송시 네트워크 대역폭을 최소화 하는 'delta encoding algorithm'을 구현해 rcp나 scp보다 빠르고 효율적으로 데이터를 동기화 한다. 즉 파일의 전체 데이터를 복사하는 대신 변경사항만 동기화해서 빠르게 복사할 수 있다는 것이다.

rsync 설치

대부분의 리눅스 배포판이나 OSX에는 기본 설치가 되어 있다. 하지만 일부 리눅스를 최소 설치 옵션으로 설치했다면 rsync가 포함되지 않았을 수 있다. 이 경우 yum이나 apt 등으로 설치해주면 된다.

$ sudo yum install rsync
# 혹은
$ sudo apt install rsync

rsync 사용법

$ rsync [OPTIONS] [SOURCE] [TARGET]

rsync 명령어는 로컬과 로컬, 로컬과 리모트, 리모트와 로컬 사이의 파일 복사를 지원한다.

예를 들면

# 로컬 데이터를 로컬에 복사
$ rsync -avh /home/user/data /home/new_user/backup
# 로컬의 데이터를 리모트로 복사
$ rsync -avh /home/user/data remote_user@remotehost:/home/remote_user/backup
# ssh 포트가 다른 경우
$ rsync -avh -e "ssh -p 123" /home/user/data remote_user@remotehost:/home/remote_user/backup
# 리모트 데이터를 로컬로 가져옴
$ rsync -avh remote_user@remotehost:/home/remote_user/backup /home/user/data

cp 명령처럼 SOURCE와 TARGET 순으로 파일의 경로를 주면된다. 만약 SOURCE나 TARGET이 리모트에 있는 파일 경로라면, "[USER]@[HOST]:[PATH]" 형식으로 입력해주면된다. 콜론(:)은 빼먹지 않도록 유의해야한다.

rsync 옵션

man 페이지를 보면 rsync의 옵션이 참 많다. 하지만 그 중에서 자주 사용되는 옵션은 다음과 같다.

옵션 설명
-v 자세한 정보를 출력 (verbose)
-z 데이터 압축
-r 재귀적으로 하위 디렉토리까지 복사
(단, 전송할 때 타임스탬프나 퍼미션을 보존하지는 않는다)
-a Archive mode, -rlptgoD 옵션을 적용한 것과 같다.
-h Human-readable format
-t 타임스탬프 보존
-l 심볼릭 링크 보존
-p 파일의 퍼미션 보존
-g 그룹 속성 보존
-o 소유자 속성 보존
-D --devices --specials 옵션과 같음, Device 관련 파일과 특수 파일(FIFO, Named Socket) 복사

CentOS 조회한 Man 페이지에 있는 옵션 설명은 다음과 같다.

-v, --verbose increase verbosity
--info=FLAGS fine-grained informational verbosity
--debug=FLAGS fine-grained debug verbosity
--msgs2stderr special output handling for debugging
-q, --quiet suppress non-error messages
--no-motd suppress daemon-mode MOTD (see caveat)
-c, --checksum skip based on checksum, not mod-time & size
-a, --archive archive mode; equals -rlptgoD (no -H,-A,-X)
--no-OPTION turn off an implied OPTION (e.g. --no-D)
-r, --recursive recurse into directories
-R, --relative use relative path names
--no-implied-dirs don't send implied dirs with --relative
-b, --backup make backups (see --suffix & --backup-dir)
--backup-dir=DIR make backups into hierarchy based in DIR
--suffix=SUFFIX backup suffix (default ~ w/o --backup-dir)
-u, --update skip files that are newer on the receiver
--inplace update destination files in-place
--append append data onto shorter files
--append-verify --append w/old data in file checksum
-d, --dirs transfer directories without recursing
-l, --links copy symlinks as symlinks
-L, --copy-links transform symlink into referent file/dir
--copy-unsafe-links only "unsafe" symlinks are transformed
--safe-links ignore symlinks that point outside the tree
--munge-links munge symlinks to make them safer
-k, --copy-dirlinks transform symlink to dir into referent dir
-K, --keep-dirlinks treat symlinked dir on receiver as dir
-H, --hard-links preserve hard links
-p, --perms preserve permissions
-E, --executability preserve executability
--chmod=CHMOD affect file and/or directory permissions
-A, --acls preserve ACLs (implies -p)
-X, --xattrs preserve extended attributes
-o, --owner preserve owner (super-user only)
-g, --group preserve group
--devices preserve device files (super-user only)
--copy-devices copy device contents as regular file
--specials preserve special files
-D same as --devices --specials
-t, --times preserve modification times
-O, --omit-dir-times omit directories from --times
-J, --omit-link-times omit symlinks from --times
--super receiver attempts super-user activities
--fake-super store/recover privileged attrs using xattrs
-S, --sparse handle sparse files efficiently
--preallocate allocate dest files before writing
-n, --dry-run perform a trial run with no changes made
-W, --whole-file copy files whole (w/o delta-xfer algorithm)
-x, --one-file-system don't cross filesystem boundaries
-B, --block-size=SIZE force a fixed checksum block-size
-e, --rsh=COMMAND specify the remote shell to use
--rsync-path=PROGRAM specify the rsync to run on remote machine
--existing skip creating new files on receiver
--ignore-existing skip updating files that exist on receiver
--remove-source-files sender removes synchronized files (non-dir)
--del an alias for --delete-during
--delete delete extraneous files from dest dirs
--delete-before receiver deletes before xfer, not during
--delete-during receiver deletes during the transfer
--delete-delay find deletions during, delete after
--delete-after receiver deletes after transfer, not during
--delete-excluded also delete excluded files from dest dirs
--ignore-missing-args ignore missing source args without error
--delete-missing-args delete missing source args from destination
--ignore-errors delete even if there are I/O errors
--force force deletion of dirs even if not empty
--max-delete=NUM don't delete more than NUM files
--max-size=SIZE don't transfer any file larger than SIZE
--min-size=SIZE don't transfer any file smaller than SIZE
--partial keep partially transferred files
--partial-dir=DIR put a partially transferred file into DIR
--delay-updates put all updated files into place at end
-m, --prune-empty-dirs prune empty directory chains from file-list
--numeric-ids don't map uid/gid values by user/group name
--usermap=STRING custom username mapping
--groupmap=STRING custom groupname mapping
--chown=USER:GROUP simple username/groupname mapping
--timeout=SECONDS set I/O timeout in seconds
--contimeout=SECONDS set daemon connection timeout in seconds
-I, --ignore-times don't skip files that match size and time
--size-only skip files that match in size
--modify-window=NUM compare mod-times with reduced accuracy
-T, --temp-dir=DIR create temporary files in directory DIR
-y, --fuzzy find similar file for basis if no dest file
--compare-dest=DIR also compare received files relative to DIR
--copy-dest=DIR ... and include copies of unchanged files
--link-dest=DIR hardlink to files in DIR when unchanged
-z, --compress compress file data during the transfer
--compress-level=NUM explicitly set compression level
--skip-compress=LIST skip compressing files with suffix in LIST
-C, --cvs-exclude auto-ignore files in the same way CVS does
-f, --filter=RULE add a file-filtering RULE
-F same as --filter='dir-merge /.rsync-filter'
repeated: --filter='- .rsync-filter'
--exclude=PATTERN exclude files matching PATTERN
--exclude-from=FILE read exclude patterns from FILE
--include=PATTERN don't exclude files matching PATTERN
--include-from=FILE read include patterns from FILE
--files-from=FILE read list of source-file names from FILE
-0, --from0 all *from/filter files are delimited by 0s
-s, --protect-args no space-splitting; wildcard chars only
--address=ADDRESS bind address for outgoing socket to daemon
--port=PORT specify double-colon alternate port number
--sockopts=OPTIONS specify custom TCP options
--blocking-io use blocking I/O for the remote shell
--outbuf=N|L|B set out buffering to None, Line, or Block
--stats give some file-transfer stats
-8, --8-bit-output leave high-bit chars unescaped in output
-h, --human-readable output numbers in a human-readable format
--progress show progress during transfer
-P same as --partial --progress
-i, --itemize-changes output a change-summary for all updates
-M, --remote-option=OPTION send OPTION to the remote side only
--out-format=FORMAT output updates using the specified FORMAT
--log-file=FILE log what we're doing to the specified FILE
--log-file-format=FMT log updates using the specified FMT
--password-file=FILE read daemon-access password from FILE
--list-only list the files instead of copying them
--bwlimit=RATE limit socket I/O bandwidth
--write-batch=FILE write a batched update to FILE
--only-write-batch=FILE like --write-batch but w/o updating dest
--read-batch=FILE read a batched update from FILE
--protocol=NUM force an older protocol version to be used
--iconv=CONVERT_SPEC request charset conversion of filenames
--checksum-seed=NUM set block/file checksum seed (advanced)
-4, --ipv4 prefer IPv4
-6, --ipv6 prefer IPv6
--version print version number
(-h) --help show this help (see below for -h comment)
Rsync can also be run as a daemon, in which case the following options are accepted:
--daemon run as an rsync daemon
--address=ADDRESS bind to the specified address
--bwlimit=RATE limit socket I/O bandwidth
--config=FILE specify alternate rsyncd.conf file
-M, --dparam=OVERRIDE override global daemon config parameter
--no-detach do not detach from the parent
--port=PORT listen on alternate port number
--log-file=FILE override the "log file" setting
--log-file-format=FMT override the "log format" setting
--sockopts=OPTIONS specify custom TCP options
-v, --verbose increase verbosity
-4, --ipv4 prefer IPv4
-6, --ipv6 prefer IPv6
-h, --help show this help (if used after --daemon)

댓글