suamikim
suamikim

Reputation: 5329

Pass dynamically generated parameters to command inside script

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?

Upvotes: 4

Views: 2187

Answers (1)

anubhava
anubhava

Reputation: 786261

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.

Upvotes: 5

Related Questions