Rsync syntax error when run from bash script

You are passing your option list as a single argument, when it needs to be passed as a list of arguments. In general, you should use an array in bash to hold your arguments, in case any of them contain whitespace. Try the following:

mkdir -p "/backup/$HOST/$NAME/$TODAY"
#source directory
SRC="https://stackoverflow.com/questions/22030280/$MNT"
#link directory
LNK="/backup/$HOST/$NAME/$LAST/"
#target directory
TRG="/backup/$HOST/$NAME/$TODAY/"
#rsync options
OPTS=( "-aAXv" "--delete" "--progress" "--link-dest=$LNK" )

#run the rsync command
echo "rsync $OPT1 $SRC $TRG"
rsync "${OPTS[@]}" "$SRC" "$TRG" > /var/log/backup/backup.rsync.log 2>&1

An array expansion ${OPTS[@]}, when quoted, is treated specially as a sequence of arguments, each of which is quoted individually to preserve any whitespace or special characters in the individual elements. If arr=("a b" c d), then echo "${arr[@]}" is the same as

echo "a b" "c" "d"

rather than

echo "a b c d"

This will not work in a shell that doesn’t support arrays, but then, arrays were invented because there wasn’t a safe way (that is, without using eval) to handle this use case without them.

Leave a Comment