Rsync syntax error when run from bash script

后端 未结 3 1208
日久生厌
日久生厌 2020-12-07 04:24

I have been working on a backup script that uses rsync to do an incremental backup.

I have tested the following rsync command manually, and it runs and completes a b

3条回答
  •  太阳男子
    2020-12-07 04:58

    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="$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.

提交回复
热议问题