Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash: rsync with options as variable

Tags:

bash

ssh

rsync

I am writing bash script, which in some part will rsync files over ssh. Unfortunately I am facing problem with keeping rsync options as variable. Please take a look below:

    # variables
    directory="/etc"
    backupDirectory="/backup"
    incrementalBackup="/incremental"
    options="-a -e 'ssh -p 10022' -b --backup-dir=$incrementalBackup --delete"
    # rsync
    rsync $options user@server:$directory $backupDirectory

Unfortunately above script fails with rsync error:

    Unexpected remote arg: user@server:/etc
    rsync error: syntax or usage error (code 1) at main.c(1201) [sender=3.0.6]

What I saw during script debugging is the fact, that ssh options ('ssh -p 10022') are treated as rsync options. The question is how to pass correctly those additional ssh settings into rsync? Thanks in advance for a tip.

like image 241
Piotr Avatar asked Oct 07 '13 08:10

Piotr


1 Answers

Use an array; it's why they were added to bash:

# variables
directory="/etc"
backupDirectory="/backup"
incrementalBackup="/incremental"
options=(-a -e 'ssh -p 10022' -b --backup-dir="$incrementalBackup" --delete)
# rsync
rsync "${options[@]}" user@server:"$directory" "$backupDirectory"

eval is not a safe option to use; it isn't limited to just evaluating the quotations you intend it to, but will evaluate any code. It might work for your current situation, but changes to the value of options might bring unforeseen consequences, and it's generally a bad idea to get into the habit of using eval when it isn't necessary.

like image 86
chepner Avatar answered Sep 22 '22 09:09

chepner