Shell Script: creating a variable with options inside

I have a rsync command with following parameters:

rsync -avz --{partial,stats,delete,exclude=".*"}

I want to put that parameters inside a variable to reuse it after in the script. Something like this:

VAR=rsync -avz --{partial,stats,delete,exclude=".*"}
$VAR /dir1 /dir2

I’ve tried with quotes, single quotes, brackets, without any success.


Putting a complex command in a variable is a never a recommended approach. See BashFAQ/050 – I’m trying to put a command in a variable, but the complex cases always fail!

Your requirement becomes really simple, if you just decide to use a function instead of a variable and pass arguments to it.

Something like

rsync_custom() {
    [ "$#" -eq 0 ] && { printf 'no arguments supplied' >&2; exit 1 ; }
    rsync -avz --{partial,stats,delete,exclude=".*"} "[email protected]"

and now pass the required arguments to it as

rsync_custom /dir1 /dir2

The function definition is quite simple in a way, we first check the input argument count using the variable $# which shouldn’t be zero. We throw a error message saying that no arguments are supplied. If there are valid arguments, then "[email protected]" represents the actual arguments supplied to the function.

If this is a function you would be using pretty frequently i.e. in scripts/command-line also, add it to the shell startup-files, .bashrc, .bash_profile for instance.

Or as noted, it may be worthwhile to expand the brace expansion to separate args for a better readability as

rsync_custom() {
    [ "$#" -eq 0 ] && { printf 'no arguments supplied' >&2; exit 1 ; }
    rsync -avz --partial --stats --delete --exclude=".*" "[email protected]"

Leave a Reply

Your email address will not be published. Required fields are marked *