1

I'm new to scripting and would like to understand how to print out the variables based on boolean logic.

#!/bin/bash

# set variables
WEBAPPS_YES="Successfully synced webapps folder"
WEBAPPS_NO="Could not sync webapps folder"
RSYNC_YES="Successfully synced rsync log file"
RSYNC_NO="Could not sync rsync log file"

# Command to rsync 'webapps' folder and write to a log file
rsync -azvh ~/webapps -e ssh user@something.com:/home/directories >> /path/to/rsync.log 2>&1

# Command to rsync 'rsync.log' to a log file on backup server 'Larry'
rsync -azvh --delete ~/rsync.log -e ssh user@something.com:/path/to/logs

if [ $? -eq 0 ]
 then
  echo 
  exit 0
else
  echo  >&2
  exit 1
fi

I would like the whole if, then, else part to print out in the echo if both parts succeeded or not. I know I need some kind of logic statements but cannot figure it out.

laurent
  • 88,262
  • 77
  • 290
  • 428
eekfonky
  • 819
  • 4
  • 16
  • 33

1 Answers1

2

You can check the result after running each rsync command, and display the result afterwards. I think that would work:

# Command to rsync 'webapps' folder and write to a log file
rsync -azvh ~/webapps -e ssh user@something.com:/home/directories >> /path/to/rsync.log 2>&1
RESULT1="$?"

# Command to rsync 'rsync.log' to a log file on backup server 'Larry'
rsync -azvh --delete ~/rsync.log -e ssh user@something.com:/path/to/logs
RESULT2="$?"

if [ "$RESULT1" != "0" ]; then
    echo "$WEBAPPS_NO"
else
    echo "$WEBAPPS_YES"
fi

if [ "$RESULT2" != "0" ]; then
    echo "$RSYNC_NO"
else
    echo "$RSYNC_YES"
fi
laurent
  • 88,262
  • 77
  • 290
  • 428
  • That's a great idea! thanks! Would it be possible to print which one failed based on the variables above though? So I could have WEBAPPS_YES "but" RSYNC_NO. That kind of thing? – eekfonky Oct 04 '16 at 11:15
  • Sure, RESULT1 and RESULT2 will basically hold "0" is the command succeeded, so you can inspect that and display the result accordingly. See updated answer. – laurent Oct 04 '16 at 11:19
  • I'll give it a go and let you know. Thank you for the help – eekfonky Oct 04 '16 at 11:20
  • please explain this `rsync -azvh ~/webapps -e ssh user@something.com:/home/directories >> /path/to/rsync.log 2>&1 RESULT1="$?"` command. – George Udosen Apr 04 '19 at 07:23
  • @GeorgeUdosen, what part? The rsync flags are documented in the man page, and the rest is standard shell syntax. – laurent Apr 04 '19 at 08:39
  • Please this `>> /path/to/rsync.log 2>&1 RESULT1="$?"` part! Excuse my inexperience. – George Udosen Apr 04 '19 at 08:47
  • `2>&1` is to redirect both stdout and stderr to the log file (see https://stackoverflow.com/a/876242/561309), and `RESULT1="$?"` is to the save the error code to the `RESULT1 variable` (see https://stackoverflow.com/a/90435/561309) – laurent Apr 04 '19 at 11:27