Search code examples
bashrsyncbsd

Bash double quotes inside double quotes BSD


Similar thread:

How can I escape a double quote inside double quotes?

I have a freebsd box with GNU bash, version 4.4.0(0)-release.

On this box there is a shell script running rsync, this script needs to specify an rsync path parameter which has space inside it.

dqt='"'

RSYNC="/usr/local/bin/rsync -avzn --rsync-path=${dqt}sudo rsync${dqt}"

The interpreter is bash but just to make sure I have tried it with specifically bash -x and here is what I get:

+ /usr/local/bin/rsync -avzn '--rsync-path="sudo' 'rsync"' --numeric-ids --delete ...

Which of course going to lead to rsync error: syntax or usage error. Any ideas how to fix this?

Run rsync fine as:

rsync-path="sudo rsync"


Solution

  • Your rsync command seems to have been word-split. You can't store a full command in a variable, you have to use an array:

    RSYNC_ARR=( /usr/local/bin/rsync -avzn --rsync-path="sudo rsync" )
    
    "${RSYNC_ARR[@]}" # the double quotes are mandatory here
    

    A little test to see the difference:

    #!/bin/bash
    
    RSYNC='/usr/local/bin/rsync -avzn --rsync-path="sudo rsync"'
    
    RSYNC_ARR=( /usr/local/bin/rsync -avzn --rsync-path=sudo\ rsync )
    
    set -x
    
    : $RSYNC
    #+ : /usr/local/bin/rsync -avzn '--rsync-path="sudo' 'rsync"'
    
    : ${RSYNC_ARR[@]}
    #+ : /usr/local/bin/rsync -avzn --rsync-path=sudo rsync
    
    : "$RSYNC"
    #+ : '/usr/local/bin/rsync -avzn --rsync-path="sudo rsync"'
    
    : "${RSYNC_ARR[@]}"
    #+ : /usr/local/bin/rsync -avzn '--rsync-path=sudo rsync'