Computer >> 컴퓨터 >  >> 프로그래밍 >> Bash 프로그래밍

Linux rsync 명령어 완벽 가이드: 구문과 실전 예제 총정리

rsync(remote synchronization, 원격 동기화)은 로컬 저장 디스크 사이에서도, 네트워크를 통해서도 파일을 동기화할 수 있는 강력한 파일 복사 도구입니다.

rsync가 널리 사용되는 이유는 단순합니다. 성능이 매우 뛰어나기 때문입니다. 주로 파일 백업, 여러 파일 서버 간 최신 상태 유지, 웹 애플리케이션의 코드와 정적 자산(assets)을 서버에 배포하는 용도로 활용됩니다.

rsync는 접근 가능한 거의 모든 파일을 복사할 수 있으며, 파일 크기와 수정 날짜를 기준으로 변경된 내용과 업데이트가 필요한 항목을 판별해 동기화를 수행합니다.

rsync는 기능이 방대한 명령어입니다. 이 가이드에서는 가장 많이 쓰이는 활용 시나리오를 중심으로 실질적인 예제를 소개하며, rsync를 시작하는 데 도움을 드립니다.

구문(Syntax)

rsync OPTIONS SOURCE DESTINATION

각 항목의 의미는 다음과 같습니다:

  • OPTIONS: 아래 목록에서 선택한 옵션들로, 공백으로 구분하여 나열
  • SOURCE: 동기화할 파일 또는 폴더의 원본 경로. 원격 호스트 정보를 포함할 수 있음
  • DESTINATION: 파일 또는 폴더를 동기화할 대상 경로. 원격 호스트 정보를 포함할 수 있음
  • SOURCE와 DESTINATION의 순서가 매우 중요! 순서를 바꾸면 데이터가 의도치 않게 삭제될 수 있습니다.

주요 옵션

다음은 rsync 매뉴얼에서 발췌한 자주 사용되는 옵션들입니다.

무엇을 복사할지 지정하는 옵션:

-r, --recursive             Recurse into directories
-R, --relative              Use relative path names
    --exclude=PATTERN       Exclude files matching PATTERN
    --exclude-from=FILE     Read exclude patterns from FILE
-I, --ignore-times          Don't exclude files that match length and time
    --size-only             Only use file size when determining if a file should be transferred
    --modify-window=NUM     Timestamp window (seconds) for file match (default=0)
    --include=PATTERN       Don't exclude files matching PATTERN
    --include-from=FILE     Read include patterns from FILE

복사 방식을 지정하는 옵션:

-n, --dry-run               Perform a trial run with no changes made
-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 links outside the destination tree
    --munge-links           Munge symlinks to make them safer
-H, --hard-links            Preserve hard links
    --devices               Preserve device files (super-user only)
    --specials              Preserve special files
-D, --devices --specials    Preserve devices (super-user only) +files
-g, --group                 Preserve group
-o, --owner                 Preserve owner (super-user only)
-p, --perms                 Preserve permissions
    --remove-source-files   Sender removes synchronized files (non-dir)
-t, --times                 Preserve times
-S, --sparse                Handle sparse files efficiently
-x, --one-file-system       Don't cross filesystem boundaries
-B, --block-size=SIZE       Force a fixed checksum block-size (default 700)
-e, --rsh=COMMAND           Specify rsh replacement
    --rsync-path=PATH       Specify path to rsync on the remote machine
    --numeric-ids           Don't map uid/gid values by user/group name
    --timeout=SECONDS       Set IO timeout in seconds
-W, --whole-file            Copy whole files, no incremental checks

대상(Destination) 관련 옵션:

-a, --archive               Archive mode equals -rlptgoD (no -H,-A,-X)
-b, --backup                Make backups (see --suffix & --backup-dir)
    --backup-dir=DIR        Make backups into this directory
-z, --compress              Compress file data during the transfer
-c, --checksum              Skip based on checksum, not mod-time & size
-C, --cvs-exclude           Auto ignore files in the same way CVS does
    --existing              Only update files that already exist
    --delete                Delete files that don't exist on the sending side
    --delete-excluded       Also delete excluded files on the receiving side
    --delete-after          Receiver deletes after transfer, not during
    --force                 Force deletion of directories even if not empty
    --ignore-errors         Delete even if there are IO errors
    --max-delete=NUM        Don't delete more than NUM files
    --log-file-format=FMT   Log file transfers using specified format
    --partial               Keep partially transferred files
    --progress              Show progress during transfer
-P                          Equivalent to --partial --progress
    --stats                 Give some file transfer stats
-T  --temp-dir=DIR          Create temporary files in directory DIR
    --compare-dest=DIR      Also compare destination files relative to DIR
-u, --update                Update only (don't overwrite newer files)

기타 옵션:

    --address=ADDRESS       Bind to the specified address
    --blocking-io           Use blocking IO for the remote shell
    --bwlimit=KBPS          Limit I/O bandwidth, KBytes per second
    --config=FILE           Specify alternate rsyncd.conf file (daemon)
    --daemon                Run as a rsync daemon
    --no-detach             Do not detach from the parent (daemon)
    --password-file=FILE    Get daemon-access password from FILE
    --port=PORT             Specify alternate rsyncd port number
-f, --read-batch=FILE       Read batch file
-F, --write-batch=FILE      Write batch file
    --version               Print version number
-v, --verbose               Increase verbosity
-q, --quiet                 Decrease verbosity
-4, --ipv4                  Prefer IPv4
-6, --ipv6                  Prefer IPv6
-h, --help                  Show this help screen

모든 옵션의 전체 목록이 필요하다면 다음 명령으로 rsync 사용자 매뉴얼을 확인하세요:

man rsync

실전 예제

아래 예제에서는 각 옵션의 의미를 반복해서 설명하지 않습니다. 옵션이 확실하지 않다면 위의 옵션 목록을 다시 참고하세요. 잘못된 명령을 실행하면 소중한 데이터를 잃을 수 있습니다!

로컬 → 로컬 (단일 파일)

로컬 머신에서 한 디렉터리의 단일 파일을 다른 디렉터리로 동기화하는 방법입니다:

rsync -zvh /path/to/my-file.tar /path/to/destination/

이후의 모든 예제는 가장 일반적인 사용 시나리오인 디렉터리 동기화를 중심으로 설명합니다.

로컬 → 로컬 (디렉터리)

같은 머신 안에서 한 디렉터리의 모든 파일을 다른 디렉터리로 동기화합니다:

rsync -avzh /path/to/source /path/to/destination

-avzh는 무엇일까요? 여러 옵션을 하나로 묶어 표기한 것입니다. -a -v -z -h를 각각 입력하는 것보다 빠르게 입력할 수 있을 뿐입니다.

로컬 → 원격 (디렉터리)

네트워크를 통해 로컬 소스 디렉터리의 모든 파일을 원격 컴퓨터의 대상 경로로 동기화합니다:

rsync -avz /path/to/source/ user@192.168.1.11:/path/at/destination/

참고 사항:

  • user: 원격 시스템의 사용자 계정
  • /path/to/source/: 로컬 컴퓨터의 소스 디렉터리 경로
  • 192.168.1.11: 원격 시스템의 IP 주소 — IP 주소 또는 호스트명을 사용할 수 있습니다
  • /path/at/destination/: 원격 파일 시스템상의 대상 경로
  • 동기화는 rsync 데몬을 통해 수행됩니다

SSH를 이용한 로컬 → 원격 (디렉터리)

-e 옵션을 사용하면 rsync가 사용할 프로토콜을 직접 지정할 수 있습니다. SSH를 지정하면 파일을 안전하게 암호화하여 전송할 수 있습니다:

rsync -avzh -e ssh /path/to/source/ user@192.168.1.11:/path/at/destination/

원격 → 로컬 (디렉터리)

네트워크를 통해 원격 컴퓨터의 소스 디렉터리에 있는 모든 파일을 로컬 컴퓨터의 대상 경로로 동기화합니다:

rsync -avzh user@192.168.1.11:/path/to/source /path/to/destination

참고 사항:

  • user: 원격 시스템의 사용자 계정
  • 192.168.1.11: 원격 시스템의 IP 주소 — IP 주소 또는 호스트명을 사용할 수 있습니다
  • /path/to/source: 원격 파일 시스템상의 경로
  • /path/to/destination: 로컬 컴퓨터의 대상 경로
  • 동기화는 rsync 데몬을 통해 수행됩니다

SSH를 이용한 원격 → 로컬 (디렉터리)

rsync -avzh -e ssh user@192.168.1.11:/path/to/source /path/to/destination

단일 파일 역시 디렉터리와 마찬가지로 로컬→원격, 원격→로컬, 그리고 SSH를 통한 방식으로 동기화할 수 있습니다.

동기화 시 추가로 고려할 사항

대역폭 제한

인터넷을 통해 동기화한다면 대역폭 사용량을 제한하여 네트워크의 다른 서비스 속도가 느려지지 않도록 하는 것이 좋습니다:

rsync -avz --bwlimit 512 /path/to/source/ user@192.168.1.11:/path/at/destination/

삭제 처리

소스에서 파일이나 폴더가 삭제되었지만 대상에는 여전히 남아 있다면, --delete 옵션으로 대상의 해당 파일을 삭제하여 소스와 완전히 동일한 미러를 만들 수 있습니다. 데이터가 실제로 삭제되므로 이 옵션을 사용하기 전에 반드시 신중하게 확인하세요:

rsync -avz --delete /path/to/source/ user@192.168.1.11:/path/at/destination/

파일 포함 및 제외

파일 패턴 매칭을 통해 특정 파일만 포함하거나 제외할 수 있습니다. 동기화하고 싶지 않은 파일이 있다면 제외하면 됩니다:

rsync -avz -e ssh --exclude '*' --include 'keep*' /path/to/source/ user@192.168.1.11:/path/at/destination/

위 rsync 명령은 'keep'으로 시작하는 파일과 디렉터리만 동기화하고, 나머지 모든 파일과 디렉터리(*)는 제외합니다.

드라이 런(Dry Run) 활용

드라이 런(--dry-run)은 어떤 파일이 변경될지 출력만 할 뿐 실제로는 아무 작업도 수행하지 않습니다. 파일이 동기화되거나 수정되지 않으므로, 다양한 옵션을 자유롭게 실험하고 그 결과를 미리 확인할 수 있습니다:

rsync -avz --dry-run /path/to/source/ user@192.168.1.11:/path/at/destination/

마무리

시스템에서 대량의 파일을 이동할 때는 Enter 키를 누르기 전에 입력 내용을 반드시 확인하세요. 잘못된 방향으로 동기화하면 중요한 파일이 삭제될 수 있습니다!

다른 Linux 셸 명령어 관련 글도 함께 확인해 보세요.