Search code examples
bashrsyncquotes

Rsync and quotes


I wrote a bash script with the following:

SRC="dist_serv:$HOME/www/"
DEST="$HOME/www/"
OPTIONS="--exclude 'file.php'"
rsync -Cavz --delete $OPTIONS $SRC $DEST

rsync fails and I can't figure out why, although it seems to be related to the $OPTIONS variable (it works when I remove it). I tried escaping the space with a backslash (among many other things) but that didn't work. The error message is :

rsync: mkdir "/home/xxx/~/public_html/" failed: No such file or directory (2)

I tried quoting the variable, which throws another error ("unknown option" on my variable $OPTIONS):

rsync: --exclude 'xxx': unknown option
rsync error: syntax or usage error (code 1) at main.c(1422) [client=3.0.6]

Solution

  • You shouldn't put $ in front of the variable names when assigning values to them. SRC is a variable, $SRC is the value that it expands to.

    Additionally, ~ is not expanded to the path of your home directory when you put it in quotes. It is generally better to use $HOME in scripts as this variable behaves like a variable, which ~ doesn't do.

    Always quote variable expansions:

    rsync -Cavz --delete "$OPTIONS" "$SRC" "$DEST"
    

    unless there is some reason not to (there very seldom is). The shell will perform word splitting on them otherwise.

    User @Fred points out that you can't use double quotes around $OPTIONS (in in comments below), but it should be ok if you use OPTIONS='--exclude="file.php"' (note the =).