0

I've got some options for commands stored in variable. Unfortunately whenever there is a space bash treats that as variable separator despite string being in quotes.

I am aware, that proper way of doing it is using arrays in bash, but this situation I've encountered is based on legacy scripts which are deploying code on commit in git. Unfortunately I have to stay with string-in-variable solution, which was doing fine till there was a need to use space in one of arguments (take a look on example, there is --filter='- /logs/' parameter.

Example script:

#!/bin/bash

RSYNC_OPTS="-r --delete --exclude .env --filter='- /logs/' --links"
mkdir a b
rsync $RSYNC_OPTS a b

I got following error:

Unknown filter rule: `'-' rsync error: syntax or usage error (code 1) at exclude.c(927) [client=3.1.3]

As far as I understand, space after --filter='- acted like argument separator despite being used in single quotes.

Until now I tried:

  • quote mode for variable: ${RSYNC_OPTS@Q}
  • Escaping space or single quotes in RSYNC_OPTS variable
  • Changing single quotes with double ones

How to make bash interpret string in quote properly when sending it as string in variable? I hope that there will be solution that does not involve changing RSYNC_OPTS to something else than single string text variable.

DevilaN
  • 1,317
  • 10
  • 21

2 Answers2

4

For such cases, bash arrays is the proper solution.

RSYNC_OPTS=(-r --delete --exclude .env --filter='- /logs/' --links)
rsync "${RSYNC_OPTS[@]}" a b
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • Yeah. I know, but I am getting those options as string from: `$(git config --get "deploy.${branch}.opts)` as a string. Although thank you for your input. – DevilaN Feb 05 '19 at 10:38
0

Try with "$RSYNC_OPTS" (suppress globbing) and also use eval, eg :

eval rsync "$RSYNC_OPTS" a b
nullPointer
  • 4,419
  • 1
  • 15
  • 27
  • Have you tried your answer? I've provided example script for testing purposes and it seems that `"$RSYNC_OPTS"` is treated as single argument to rsync and resulting in `unknown option` error – DevilaN Feb 05 '19 at 10:04
  • try with eval as per updated answer – nullPointer Feb 05 '19 at 10:19
  • 1
    See [Why should eval be avoided in Bash, and what should I use instead?](https://stackoverflow.com/q/17529220/4154375). – pjh Feb 05 '19 at 10:54