0

I'm trying to save the output of a rsnapshot command to a variable, and then later use that output. The variable seems empty, however.

Here's the script. Modified for debugging.

#!/bin/bash
#Run the command `rsnapshot daily`, and show results
echo "Making backup on USB drive attached to nas."
echo "running command 'rsnapshot -v daily'..."
rsnapshotresult=$( { rsnapshot -v daily; } )
if [ $? -ne 0 ]
then
    echo "rsnapshotdaily.sh error"
    echo $rsnapshotresult
    echo "done"
fi

Now, I run this script (file rsnapshotdaily.sh) on the command line. The output in the terminal:

[~] # /folder/rsnapshotdaily.sh
Making backup on USB drive attached to nas.
running command 'rsnapshot -v daily'...
Could not open logfile /share/USBDisk1/rsnapshotlog for writing
Do you have write permission for this file?
rsnapshotdaily.sh error

done

There is output shown in the terminal, but appently directly from the the rsnapshot command, and none appears stored in the variable rsnapshotresult.

What am I doing wrong?

4
  • 2
    $( ... ) captures stdout only, and stdout is intended to contain only a program's result. Informational, error, prompt, and status messages should be written to stderr (and password prompts historically/typically bypass both and go straight to the TTY). Commented Oct 29, 2018 at 19:36
  • 1
    BTW, in general, avoid [ $? -ne 0 ]. Consider instead if ! rsnapshot_output=$(rsnapshot -v daily 2>&1); then printf '%s\n' "rsnapshotdaily.sh error" "$rsnapshot_output" "done" >&2; fi, branching directly on exit status rather than needing to refer back to it -- this is much Commented Oct 29, 2018 at 19:37
  • (Also, avoid echo $foo, which munges whitespace/newlines/wildcards/etc as described in BashPitfalls #14; always use echo "$foo" to emit content in a variable -- or, even better, printf '%s\n' "$foo"). Commented Oct 29, 2018 at 19:39
  • Thanks guys, that cleared it up! The issue is indeed the one addressed in the question that mine is marked a duplicate of. Commented Oct 29, 2018 at 19:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.