I want to save command parameters for re-use in a variable in Bash. The reason is they are very long and I use them multiple times.
SRC_FOLDER="src folder"
DST_FOLDER="dst folder"
PARAMS="--dry-run \"$SRC_FOLDER\" \"$DST_FOLDER\""
rsync $PARAMS
The problem is the space in the src and dst folder. Rsync thinks there are 4 folders instead of 2. I think I somehow have to escape the variables in line 3.
I cannot escape the folders in line 1 and 2 because they might have been passed to my bash script by parameter and I don't know the content.
Please also note that the src and dst folders may have other special signs like *, $, \, ", '.
Is this possible without using separate variables like this:
rsync $PARAMS "$SRC_FOLDER" "$DST_FOLDER"
Is there a solution?
#!/bin/bash
rsync_args=(
--dry-run
"src folder"
"dst folder"
)
rsync "${rsync_args[@]}"
The remote path in rsync
commands is subject to word splitting.
The following example is wrong:
rsync -av ~/ user@server:'home backup 2021-12-04/'
You have to write it like this:
rsync -av ~/ user@server:'home\ backup\ 2021-12-04/'
A way for fixing it automatically is:
#!/bin/bash
remote_path='home backup 2021-12-04/'
qq="'\''"
rsync -av ~/ user@server:"'${remote_path//\'/$qq}'"