LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Bash string substitution (rsync exclude) (https://www.linuxquestions.org/questions/linux-newbie-8/bash-string-substitution-rsync-exclude-4175542675/)

vrltwe 05-15-2015 09:08 AM

Bash string substitution (rsync exclude)
 
I'm preparing a rsync script to backup from one machine to another through ssh. For this I'm successful with the following:

IP=150.163.49.15
ORIGIN=/home
DESTINATION=samba

rsync -avzP --exclude={cristiano,marcelo} root@$IP:$ORIGIN $DESTINATION/

I would like to improve it, moving the exclude part to a variable also. I've unsuccessfully tried this:

IP=150.163.49.15
ORIGIN=/home
DESTINATION=samba
EXCLUDE={cristiano,marcelo}

rsync -avzP --exclude=$EXCLUDE root@$IP:$ORIGIN $DESTINATION/

What is wrong with the EXCLUDE syntax?

warshall 05-15-2015 01:38 PM

Hi-

Your problem is that bash expands braces before variables. So your effective command line (the one rsync is actually getting) includes the literal string --exclude={cristiano,marcelo}, as opposed to the brace-expanded version of that, namely --exclude=cristiano --exclude=marcelo, which would be what you want.

You might want to use an array. I use zsh, not bash, but on my system, after
Code:

EXCLUDE=(cris marc)
,
Code:

${EXCLUDE/#/--exclude=}
expands to --exclude=cris --exclude=marc.

Hope this helps,

Andrew Warshall

jhekkanen 05-15-2015 01:51 PM

I'm assuming the Bash shell here. I'm not sure about all the details of
this but when you run the first command you are using brace expansion:

Code:

bash-4.2$ echo cmd --exclude={foo,bar}
cmd --exclude=foo --exclude=bar

Now when we introduce the variable, we can see where things go wrong:

Code:

bash-4.2$ EXCLUDE={foo,bar}
bash-4.2$ echo cmd --exclude=$EXCLUDE
cmd --exclude={foo,bar}

One option would be to use an array instead:

Code:

bash-4.2$ EXCLUDE=(foo bar)
bash-4.2$ echo cmd ${EXCLUDE[@]/#/--exclude=}
cmd --exclude=foo --exclude=bar


Keith Hedger 05-15-2015 07:15 PM

How about
Code:

EXCLUDE=$(echo --exclude={cristiano,marcelo})
echo rsync -avzP $EXCLUDE root@$IP:$ORIGIN $DESTINATION

gives
Code:

rsync -avzP --exclude=cristiano --exclude=marcelo root@150.163.49.15:/home samba


All times are GMT -5. The time now is 06:38 PM.