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?

ElRudi
  • 2,122
  • 2
  • 18
  • 33
  • 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). – Charles Duffy Oct 29 '18 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 – Charles Duffy Oct 29 '18 at 19:37
  • (Also, avoid `echo $foo`, which munges whitespace/newlines/wildcards/etc as described in [BashPitfalls #14](http://mywiki.wooledge.org/BashPitfalls#echo_.24foo); always use `echo "$foo"` to emit content in a variable -- or, even better, `printf '%s\n' "$foo"`). – Charles Duffy Oct 29 '18 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. – ElRudi Oct 29 '18 at 19:44

0 Answers0