0

I'm trying to assemble an rsync command in a bash variable and then execute it. It looks something like this:

CMD="$RSYNC -a $REMOTE $LOCAL $LINK_DEST"

It gets executed like this

RSYNC_RESULT=$($CMD)

This works fine until I try to add add --rsync-path="sudo /usr/local/bin/rsync" to the mix (so that rsync runs as root on the remote).

RSYNC_PATH='--rsync-path="sudo /usr/local/bin/rsync"'
CMD="$RSYNC -a $RSYNC_PATH $REMOTE $LOCAL $LINK_DEST"

Now I get an error

Unexpected remote arg: user@remote.local:/Users/user/files/ rsync error: syntax or usage error (code 1) at main.c(1343) [sender=3.1.2]

I'm fairly certain it's connected to the quoting in the $RSYNC_PATH var and/or the $($CMD) bit, because I can paste the resulting command into a shell and it runs successfully.

Any ideas what I can do to make this work?

pkpowell
  • 19
  • 2
  • 6
  • I substituted `$($CMD)` for `eval $CMD` and it seems to work. Anyone know why? – pkpowell Jul 29 '18 at 21:39
  • This is [BashFAQ #50](http://mywiki.wooledge.org/BashFAQ/050). – Charles Duffy Jul 29 '18 at 21:45
  • 1
    ...to avoid [the security issues associated with `eval`](http://mywiki.wooledge.org/BashFAQ/048), use an array -- not a string -- to store an argument list. – Charles Duffy Jul 29 '18 at 21:47
  • A more correct invocation might look like `rsync_path=( --rsync-path="sudo /usr/local/bin/rsync" ); cmd=( rsync -a "${rsync_path[@]}" "$remote" "$local" "$link_dest" ); "${cmd[@]}"` – Charles Duffy Jul 29 '18 at 21:49
  • ...re: the use of lower-case vs all-caps variable names, see relevant POSIX spec at http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html: *The name space of environment variable names containing lowercase letters is reserved for applications. Applications can define any environment variables with names from this name space without modifying the behavior of the standard utilities*; keep in mind that setting regular shell variables overwrites any preexisting like-named environment variable. – Charles Duffy Jul 29 '18 at 21:49
  • Thanks Charles, works perfectly. Can I mark a comment as a solution? – pkpowell Jul 30 '18 at 06:41
  • No need -- the comments just summarize advice from the linked duplicates; since it's closed as a duplicate, the question is marked as not needing a separate answer. – Charles Duffy Jul 30 '18 at 22:59

0 Answers0