rsync

Remote file copy (Synchronize file trees)

Syntax:
       rsync [options] Source [Source...] Destination

Quick basic example: backup the desktop to the mybackups folder on an external hard drive:

   rsync -rlpt --stats  Desktop /volumes/LaCieDrive/mybackups

   Options used above:
     -r = Recursive, traverse into subdirectories
     -l = Treat symlinks as symlinks; don’t follow them
     -p = Preserve permissions
     -t = Preserve creation and modification dates and times
     --stats = Show file transfer statistics

Options

What to copy:

     --exclude=PATTERN       Exclude files matching PATTERN
     --exclude-from=FILE     Exclude patterns listed in FILE
 -E, --extended-attributes   Copy extended attributes (xattr)
     --files-from=FILE       Read list of source-file names from FILE
 -f, --filter=RULE           add a file-filtering RULE
 -F                          same as --filter='dir-merge /.rsync-filter'
                             repeated: --filter='- .rsync-filter'
 -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

     --include=PATTERN       Don’t exclude files matching PATTERN
     --include-from=FILE     Don’t exclude patterns listed in FILE
     --max-size=SIZE         Don’t transfer any file larger than SIZE
     --min-size=SIZE         Don’t transfer any file smaller than SIZE
     --modify-window=NUM     Timestamp window (seconds) for file match (default=0)
 -m, --prune-empty-dirs      prune empty directory chains from the file-list
     --modify-window=NUM     Compare mod-times with reduced accuracy
 -p, --perms                 Preserve permissions
     --specials              Preserve special files
 -r, --recursive             Recursive, traverse into subdirectories
 -R, --relative              Use relative path names
     --no-implied-dirs       Don’t send implied dirs with --relative
     --size-only             Skip files that match in size

How to copy it:

 -e, --rsh=COMMAND           Specify rsh replacement
     --rsync-path=PATH       Specify path to rsync on the remote machine
     --chmod=CHMOD           Affect file and/or directory permissions
 -d, --dirs                  Transfer directories without recursing
 -D, --devices               Preserve devices (root only)
     --executability         Preserve the file’s executability
 -g, --group                 Preserve group
 -H, --hard-links            Preserve hard links
 -l, --links                 Treat symlinks as symlinks; don’t follow them
 -L, --copy-links            Copy the referent of symlinks
     --copy-unsafe-links     Copy links outside the source tree
     --safe-links            Ignore links outside the destination tree
 -n, --dry-run               Show what would have been transferred
     --numeric-ids           Don’t map uid/gid values by user/group name
 -o, --owner                 Preserve owner (root only)
 -O, --omit-dir-times        Omit directories when preserving times
     --partial               Keep partially transferred files
     --partial-dir=DIR       Put a partially transferred file into DIR
     --delay-updates         Put all updated files into place at transfer’s end

 -t, --times                 Preserve creation and modification dates and times
     --timeout=TIME          Set IO timeout in seconds
 -S, --sparse                Handle sparse files efficiently
 -W, --whole-file            Copy whole files, no incremental checks
 -x, --one-file-system       Don’t cross filesystem boundaries

Destination options:

 -a, --archive               Archive mode
 -b, --backup                Make backups (default ~ suffix)
     --backup-dir=DIR        Make backups into this directory
     --suffix=SUFFIX         Override backup suffix
 -c, --checksum              Always checksum
 -C, --cvs-exclude           Auto ignore files in the same way CVS does
     --existing              Only update files that already exist
     --ignore-existing       skip updating files that already exist on receiver

     --del                   Delete files that don’t exist on the sending side
     --delete                an alias for --delete-during
     --delete-after          Delete after transferring, not before
     --delete-before         receiver deletes before transfer (default)
     --delete-during         receiver deletes during transfer, not before
     --delete-excluded       Also delete excluded files on the receiving side

     --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
     --list-only             List the files instead of copying them
     --log-format=FORMAT     Log file transfers using specified format
     --partial               Keep partially transferred files
     --progress              Show progress during transfer
 -P                          Equivalent to --partial --progress
     --stats                 Show file transfer statistics
     --remove-source-files   Sender removes synchronized files (non-dirs)
 -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)
     --inplace               Update destination files in-place (SEE MAN PAGE)
     --append                Append data onto shorter files.
 -z, --compress              Compress file data
     --compress-level=NUM    Explicitly set compression level

Misc Others:

 -0, --from0                 All *-from/filter files are delimited by 0s
 -4, --ipv4                  Prefer IPv4
 -6, --ipv6                  Prefer IPv6
 -8, --8-bit-output          Leave high-bit chars unescaped in output
     --address=ADDRESS       Bind address for outgoing socket to daemon
 -B, --block-size=SIZE       Force a fixed checksum block-size
     --blocking-io           Use blocking IO for the remote shell
     --bwlimit=KBPS          Limit I/O bandwidth, KBytes per second
     --cache                 Disable fcntl(F_NOCACHE)
     --config=FILE           Specify alternate rsyncd.conf file
     --daemon                Run as a rsync daemon
 -f, --read-batch=FILE       Read batch file
 -F, --write-batch           Write batch file
 -h, --help                  Show help (with no other options)
 -h, --human-readable        Output numbers in a human-readable format
 -i, --itemize-changes       output a change-summary for all updates
 -k, --copy-dirlinks         Transform symlink to a dir into referent dir
 -K, --keep-dirlinks         Treat symlinked dir on receiver as dir
     --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
     --no-detach             Do not detach from the parent
     --password-file=FILE    Get password from FILE
     --port=PORT             Specify alternate rsyncd port number
     --protocol=NUM          Force an older protocol version to be used
     --sockopts=OPTIONS      Specify custom TCP options
     --stats                 Give some file-transfer stats
     --super                 Receiver attempts super-user activities
 -T, --temp-dir=DIR          Create temporary files in directory DIR
 -v, --verbose               Increase verbosity
 -q, --quiet                 Decrease verbosity
     --version               Print version number
     --write-batch=FILE      Write a batched update to FILE
     --only-write-batch=FILE Like --write-batch but w/o updating destination
     --read-batch=FILE       Read a batched update from FILE
 -y, --fuzzy                 Find similar file for basis if no dest file
     --compare-dest=DIR      Also compare destination files relative to DIR
     --copy-dest=DIR         ... and include copies of unchanged files
     --link-dest=DIR         Hardlink to files in DIR when unchanged

Additional details about the options above can be found on the rsync options and Exit Values page.

In many cases the Source and Destination will be a directory path, however either the Source or the Destination can be on a remote host:

       [User@]Host:Source_or_Destination_directory

       [User@]Host::Source_or_Destination_directory

       rsync://[User@]Host[:Port]/Source_or_Destination_directory

Description

rsync is a program that behaves in much the same way that rcp does, but has many more options and uses the rsync remote-update protocol to greatly speed up file transfers when the destination file already exists.

The rsync remote-update protocol allows rsync to transfer just the differences between two sets of files across the network link, using an efficient checksum-search algorithm described in the technical report that accompanies this package.

Some of the additional features of rsync are:

# support for copying links, devices, owners, groups and permissions
# exclude and exclude-from options are similar to GNU tar
# a CVS exclude mode for ignoring the same files that CVS would ignore
# can use any transparent remote shell, including rsh or ssh
# does not require root privileges
# pipelining of file transfers to minimize latency costs
# support for anonymous or authenticated rsync servers (ideal for mirroring)

General

There are six different ways of using rsync. They are:

# for copying local files. This is invoked when neither source nor destination path contains a : separator

# for copying from the local machine to a remote machine using a remote shell program as the transport (such as rsh or ssh).
This is invoked when the destination path contains a single : separator.

# for copying from a remote machine to the local machine using a remote shell program. This is invoked when the source contains a : separator.

# for copying from a remote rsync server to the local machine. This is invoked when the source path contains a :: separator or a rsync:// URL.

# for copying from the local machine to a remote rsync server. This is invoked when the destination path contains a :: separator.

# for listing files on a remote machine. This is done the same way as rsync transfers except that you leave off the local destination.

In all cases (other than listing) at least one of the source and destination paths must be local.

Usage

You use rsync in the same way you use rcp. You must specify a source and a destination, one of which can be remote.

Perhaps the best way to explain the syntax is some examples:

   rsync *.c foo:Source/

This would transfer all files matching the pattern *.c from the current directory to the directory Source on the machine foo.
If any of the files already exist on the remote system then the rsync remote-update protocol is used to update the file by sending only the differences.
See the tech report for details.

   rsync -avz foo:Source/bar /data/tmp

this would recursively transfer all files from the directory Source/bar on the machine foo into the /data/tmp/bar directory on the local machine.
The files are transferred in "archive" mode, which ensures that symbolic links, devices, attributes, permissions, ownerships etc are preserved in the transfer. Additionally, compression will be used to reduce the size of data portions of the transfer.

   rsync -avz foo:Source/bar/ /data/tmp

a trailing slash on the source changes this behavior to transfer all files from the directory Source/bar on the machine foo into the /data/tmp/.
A trailing / on a source name means "copy the contents of this directory". Without a trailing slash it means "copy the directory".
This difference becomes particularly important when using the --delete option.

You can also use rsync in local-only mode, where both the source and destination don’t have a ':' in the name. In this case it behaves like an improved copy command.

  rsync somehost.mydomain.com::

this would list all the anonymous rsync modules available on the host somehost.mydomain.com. (See the following section for more details.)

Connecting to an Rsync Server

It is also possible to use rsync without using rsh or ssh as the transport. In this case you will connect to a remote rsync server running on TCP port 873.

You can establish the connection via a web proxy by setting the environment variable RSYNC_PROXY to a hostname:port pair pointing to your web proxy. Note that your web proxy’s configuration must allow proxying to port 873.

Using rsync in this way is the same as using it with rsh or ssh except that:

Some paths on the remote server will require authentication. If so then you will receive a password prompt when you connect.
You can avoid the password prompt by setting the environment variable RSYNC_PASSWORD to the password you want to use or using the --password-file option. This may be useful when scripting rsync.

WARNING: On some systems environment variables are visible to all users. On those systems using --password-file is recommended.

Running an Rsync Server

An rsync server is configured using a config file which by default is
called /etc/rsyncd.conf. Please see the rsyncd.conf(5) man page for more information.

Examples

To Backup the home directory using a cron job:

   rsync -Cavz . server64:backup

Run the above over a PPP link to a duplicate directory on machine "server64".

To synchronize samba source trees use the following Makefile targets:

   get:
   rsync -avuzb --exclude '*~' samba:samba/ .

   put:
   rsync -Cavuzb . samba:samba/

   sync: get put

this allows me to sync with a CVS directory at the other end of the link. I then do cvs operations on the remote machine, which saves a lot of time
as the remote cvs protocol isn’t very efficient.

I mirror a directory between my "old" and "new" ftp sites with the command

   rsync -az -e ssh --delete ~ftp/pub/samba/ nimbus:"~ftp/pub/tridge/samba"

this is launched from cron every few hours.

Exclude Patterns

The exclude and include patterns specified to rsync allow for flexible selection of which files to transfer and which files to skip.

rsync builds an ordered list of include/exclude options as specified on the command line. When a filename is encountered, rsync checks the name against each exclude/include pattern in turn. The first matching pattern is acted on.
If it is an exclude pattern, then that file is skipped.
If it is an include pattern then that filename is not skipped.
If no matching include/exclude pattern is found then the filename is not skipped.

Note that when used with -r (which is implied by -a), every subcomponent of every path is visited from top down, so include/exclude patterns get applied
recursively to each subcomponent.

Note also that the --include and --exclude options take one pattern each. To add multiple patterns use the --include-from and --exclude-from options
or multiple --include and --exclude options.

The patterns can take several forms. The rules are:

The +/- rules are most useful in exclude lists, allowing you to have a single exclude list that contains both include and exclude options.

If you end an exclude list with --exclude '*', note that since the algorithm is applied recursively that unless you explicitly include parent directories of files
you want to include then the algorithm will stop at the parent directories and never see the files below them.
To include all directories, use --include '*/' before the --exclude '*'.

Here are some exclude/include examples:

# --exclude "*.o" would exclude all filenames matching *.o
# --exclude "/foo" would exclude a file in the base directory called foo
# --exclude "foo/" would exclude any directory called foo.
# --exclude "/foo/*/bar" would exclude any file called bar two levels below a base directory called foo.
# --exclude "/foo/**/bar" would exclude any file called bar two or more levels below a base directory called foo.
# --include "*/" --include "*.c" --exclude "*" would include all directories and C source files
# --include "foo/" --include "foo/bar.c" --exclude "*"
would include only foo/bar.c (the foo/ directory must be explicitly included or it would be excluded by the "*")

Batch Mode

The following call generates 4 files that encapsulate the information for synchronizing the contents of target_dir with the updates found in Source_dir

$ rsync -F [other rsync options here] \ /somewhere/Source_dir /somewhere/target_dir

The generated files are labeled with a common timestamp:

# rsync_argvs.timestamp command-line arguments
# rsync_flist.timestamp rsync internal file metadata
# rsync_csums.timestamp rsync checksums
# rsync_delta.timestamp data blocks for file update & change

Symbolic Links

Three basic behaviours are possible when rsync encounters a symbolic link in the source directory.

By default, symbolic links are not transferred at all. A message "skipping non-regular" file is emitted for any symlinks that exist.

If --links is specified, then symlinks are recreated with the same target on the destination. Note that --archive implies --links.

If --copy-links is specified, then symlinks are "collapsed" by copying their referent, rather than the symlink.

rsync also distinguishes "safe" and "unsafe" symbolic links.
An example where this might be used is a web site mirror that wishes ensure the rsync module they copy does not include symbolic links to /etc/passwd in the public section of the site. Using --copy-unsafe-links will cause any links to be copied as the file they point to on the destination.
Using --safe-links will cause unsafe links to be ommitted altogether.

Diagnostics

rsync occasionally produces error messages that may seem a little cryptic.
The one that seems to cause the most confusion is "protocol version mismatch - is your shell clean?".

This message is usually caused by your startup scripts or remote shell facility producing unwanted garbage on the stream that rsync is using for its transport. The way to diagnose this problem is to run your remote shell like this:

   rsh remotehost /bin/true > out.dat

Then look at out.dat. If everything is working correctly then out.dat should be a zero length file. If you are getting the above error from rsync then you will
probably find that out.dat contains some text or data. Look at the contents and try to work out what is producing it.
The most common cause is incorrectly configured shell startup scripts (such as .cshrc or .profile) that contain output statements for non-interactive logins.

If you are having trouble debugging include and exclude patterns, then try specifying the -vv option. At this level of verbosity rsync will show why each individual file is included or excluded.

Setup

See the file README for installation instructions.

Once installed you can use rsync to any machine that you can use rsh to. rsync uses rsh for its communications, unless both the source and destination are local.

You can also specify an alternative to rsh, either by using the -e command line option, or by setting the RSYNC_RSH environment variable.

One common substitute is to use ssh, which offers a high degree of security. Note that rsync must be installed on both the source and destination machines.

Environment Variables

CVSIGNORE
    The CVSIGNORE environment variable supplements any ignore patterns in .cvsignore files.
    See the --cvs-exclude option for more details.

RSYNC_RSH
    The RSYNC_RSH environment variable allows you to override the default shell used as
    the transport for rsync. This can be used instead of the -e option.

RSYNC_PROXY
    The RSYNC_PROXY environment variable allows you to redirect your rsync client to
    use a web proxy when connecting to a rsync daemon.
    You should set RSYNC_PROXY to a hostname:port pair.

RSYNC_PASSWORD
    Setting RSYNC_PASSWORD to the required password allows you to run authenticated
    rsync connections to a rsync daemon without user intervention.
    Note that this does not supply a password to a shell transport such as ssh.

USER or LOGNAME
    The USER or LOGNAME environment variables are used to determine the default
    username sent to a rsync server.

HOME
    The HOME environment variable is used to find the user's default .cvsignore file.

FILES

/etc/rsyncd.conf

“I was the only kid in the audience who didn’t understand why Dorothy would ever want to go home. It was a mystery to me. To that awful black and white farm, with that aunt who was dressed badly, with smelly farm animals around. When she could live with winged monkeys and magic shoes and gay lions. I didn’t get it” ~ John Waters

Related macOS commands

rsync.samba.org - Download latest version (plus docs).
cp - Copy files.
install - Copy files and set attributes.
rcp - Remote file copy.
rsnapshot - Save multiple backups with rsync.
Grsync - GUI for rsync.
youtube-dl - Download video.


 
Copyright © 1999-2024 SS64.com
Some rights reserved