Bash – Error in Bash rsync script

bashrsync

A bash script has the following line

    rsync $OPTS $BACKDIR $USER@$DEST:$DESTDIR     

but one of the options is rsh='ssh -p2222'
It complains :

    rsync: -p2222': unknown option
    rsync error: syntax or usage error (code 1) at main.c(1425) [client=3.0.7]

But when I change the script to :

    echo rsync $OPTS $BACKDIR $USER@$DEST:$DESTDIR     

and manually run the printed command it works.

Please advise

Best Answer

Short answer: see BashFAQ #50.

Long answer: Putting commands (or parts of commands) into variables and then getting them back out intact is complicated. When the shell expands a variable on the command line, if the variable was in double-quotes it's not parsed (see @Dennis Williamson's answer); if it was not in quotes, spaces in it are parsed as argument breaks, but quotes and escape are not parsed (which is why you got an error about a literal quote mark in one of the args to rsync). In either case, putting quotes in the variable's value does nothing useful.

There are, however, several ways to fix your script, depending on how complex OPTS is:

  1. If --rsh is the only thing in OPTS, then double-quote it (as in Dennis Williamson's answer):

    OPTS='--rsh=ssh -p2222'
    rsync "$OPTS" "$BACKDIR" "$USER@$DEST:$DESTDIR"
    

    (Note the double-quotes around the other args as well: this is to prevent misparsing if they contain spaces, and is generally good scripting hygiene.)

  2. If the contents of OPTS are constant (or at least, the --rsh part is), then don't try to put it in a variable, just use it directly:

    rsync --rsh='ssh -p2222' $RESTOFOPTS "$BACKDIR" "$USER@$DEST:$DESTDIR"
    
  3. If neither of those simple cases apply, use an array instead of a plain variable:

    OPTS=(-x --delete --inplace)
    if [[ "$rsync_version" == 2.* ]]; then
        OPTS+=(-aE)
    else
        OPTS+=(-aNHX)
    fi
    if [[ -n "$using_rsh" ]]; then
        OPTS+=('--rsh=ssh -p2222')
    fi
    rsync "${OPTS[@]}" "$BACKDIR" "$USER@$DEST:$DESTDIR"