4

I have a script which calls the rsync command with some dynamically generated parameters but I'm having trouble passing them correctly.

Here's some excerpt:

logfile="$logDir/$(timestamp) $name.log"
echo "something" >> "$logfile"

params="-aAXz --stats -h --delete --exclude-from $exclude --log-file=$logfile $src $dest"
if [ "$silent" = "" ]; then
    params="-v $params --info=progress2"
fi
rsync $params

If the logfile is e.g. /tmp/150507 test.log, the something statement is actually written to /tmp/150507 test.log, but rsync writes its logs to /tmp/150507 (everything after the first blank removed).

If I explicitly quote the name of the logfile in the params, rsync throws an exception:

params="-aAXz --stats -h --delete --exclude-from $exclude --log-file=\"$logfile\" $src $dest"

The error:

rsync: failed to open log-file "/tmp/150507: No such file or directory (2)
Ignoring "log file" setting.

How can I generate the params dynamically without losing the ability to use blanks in the filenames?

1 Answer 1

5

More quoting needed around log file name:

declare -a params

params=(-aAXz --stats -h --delete --exclude-from "$exclude" --log-file="$logfile" "$src" "$dest")

if [[ "$silent" = "" ]]; then
    params=( -v "${params[@]}" --info=progress2 )
fi

rsync "${params[@]}"

This is the case where you should consider using BASH arrays to constitute a dynamic command line.

Sign up to request clarification or add additional context in comments.

4 Comments

Ain't that exactly what I mentioned in the 2nd half of my post (starting with "If I explicitly quote...") which leads to the rsync error?
@suamikim, no, because in that 2nd half of your post you're creating a string; in the answer here you're creating an array.
@anubhava, ...though the -v "$params" is a bit odd; you're adding the first element of the array in directly after the -v? I think a more accurate representation would be params=( -v "${params[@]}" --info=progress2 ); it's not += because the OP is replacing the prior first argument with -v.
Thanks @CharlesDuffy for your insight. It is corrected now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.