Rsync syntax error when run from bash script

后端 未结 3 1209
日久生厌
日久生厌 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:45

    This:

    rsync "$OPT1 $SRC $TRG"
    

    passes all your intended arguments lumped together as one argument, which rsync doesn't know how to deal with.

    Try this instead:

    rsync ${OPT1} ${SRC} ${TRG}
    
    0 讨论(0)
  • 2020-12-07 04:57

    The approach suggested by @chepner didn't work on my Mac OS X (10.9.4), but eval did.

    eval rsync "$OPT1 $SRC $TRG"
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题