Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rsync option in a variable

Tags:

bash

shell

rsync

I want to put command option of rsync into a variable so I can reuse it for other rsync commands. Here is what I tried but it didn't work.

roption="-a --recursive --progress --exclude='class' --delete --exclude='exclude' --exclude='.svn' --exclude='.metadata' --exclude='*.class'"
rsync "$roption" /media/CORSAIR/workspace ~/

Can any body help me figure out the problem?

Thanks,

like image 892
Son Nguyen Avatar asked Dec 10 '22 14:12

Son Nguyen


2 Answers

Use shell arrays. They're extremely useful if you want to form strings using escapes and have them be literally what is typed. Plus, security.

roption=(
    -a
    --recursive
    --progress
    --exclude='class'
    --delete
    --exclude='exclude'
    --exclude='.svn'
    --exclude='.metadata'
    --exclude='*.class'
)

rsync "${roption[@]}" /media/CORSAIR/workspace ~/

You can even add to them:

if [ "$VERBOSE" -ne 0 ]; then
    roption+=(--verbose)
fi
like image 200
amphetamachine Avatar answered Dec 28 '22 05:12

amphetamachine


Since your $roption represents more than one argument, you should use $roption, not "$roption".

Of course, using a scalar to hold multiple values is just wrong. If you are using bash, consider using an array instead:

roptions=(-a --recursive --progress --exclude='class' --delete --exclude='exclude' --exclude='.svn' --exclude='.metadata' --exclude='*.class')
rsync "${roptions[@]}" /media/CORSAIR/workspace ~
like image 39
Chris Jester-Young Avatar answered Dec 28 '22 03:12

Chris Jester-Young