I want to setup a cron job to rsync a remote system to a backup partition, something like:
bash -c 'rsync -avz --delete --exclude=proc --exclude=sys root#remote1:/ /mnt/remote1/'
I would like to be able to "set it and forget it" but what if /mnt/remote1 becomes unmounted? (After a reboot or something) I'd like to error out if /mnt/remote1 isn't mounted, rather than filling up the local filesystem.
Edit:
Here is what I came up with for a script, cleanup improvements appreciated (especially for the empty then ... else, I couldn't leave them empty or bash errors)
#!/bin/bash
DATA=data
ERROR="0"
if cut -d' ' -f2 /proc/mounts | grep -q "^/mnt/$1\$"; then
ERROR=0
else
if mount /dev/vg/$1 /mnt/$1; then
ERROR=0
else
ERROR=$?
echo "Can't backup $1, /mnt/$1 could not be mounted: $ERROR"
fi
fi
if [ "$ERROR" = "0" ]; then
if cut -d' ' -f2 /proc/mounts | grep -q "^/mnt/$1/$DATA\$"; then
ERROR=0
else
if mount /dev/vg/$1$DATA /mnt/$1/data; then
ERROR=0
else
ERROR=$?
echo "Can't backup $1, /mnt/$1/data could not be mounted."
fi
fi
fi
if [ "$ERROR" = "0" ]; then
rsync -aqz --delete --numeric-ids --exclude=proc --exclude=sys \
root#$1.domain:/ /mnt/$1/
RETVAL=$?
echo "Backup of $1 completed, return value of rsync: $RETVAL"
fi
mountpoint seems to be the best solution to this: it returns 0 if a path is a mount point:
#!/bin/bash
if [[ `mountpoint -q /path` ]]; then
echo "filesystem mounted"
else
echo "filesystem not mounted"
fi
Found at LinuxQuestions.
if cut -d' ' -f2 /proc/mounts | grep '^/mnt/remote1$' >/dev/null; then
rsync -avz ...
fi
Get the list of mounted partitions from /proc/mounts, only match /mnt/remote1 (and if it is mounted, send grep's output to /dev/null), then run your rsync job.
Recent greps have a -q option that you can use instead of sending the output to /dev/null.
A quick google led me to this bash script that can check if a filesystem is mounted. It seems that grepping the output of df or mount is the way to go:
if df |grep -q '/mnt/mountpoint$'
then
echo "Found mount point, running task"
# Do some stuff
else
echo "Aborted because the disk is not mounted"
# Do some error correcting stuff
exit -1
fi
Copy and paste the script below to a file (e.g. backup.sh).
Make the script executable (e.g. chmod +x backup.sh)
Call the script as root with the format backup.sh [username (for rsync)] [backup source device] [backup source location] [backup target device] [backup target location]
!!!ATTENTION!!! Don't execute the script as root user without understanding the code!
I think there's nothing to explain. The code is straightforward and well documented.
#!/bin/bash
##
## COMMAND USAGE: backup.sh [username] [backup source device] [backup source location] [backup target device] [backup target location]
##
## for example: sudo /home/manu/bin/backup.sh "manu" "/media/disk1" "/media/disk1/." "/media/disk2" "/media/disk2"
##
##
## VARIABLES
##
# execute as user
USER="$1"
# Set source location
BACKUP_SOURCE_DEV="$2"
BACKUP_SOURCE="$3"
# Set target location
BACKUP_TARGET_DEV="$4"
BACKUP_TARGET="$5"
# Log file
LOG_FILE="/var/log/backup_script.log"
##
## SCRIPT
##
function end() {
echo -e "###########################################################################\
#########################################################################\n\n" >> "$LOG_FILE"
exit $1
}
# Check that the log file exists
if [ ! -e "$LOG_FILE" ]; then
touch "$LOG_FILE"
chown $USER "$LOG_FILE"
fi
# Check if backup source device is mounted
if ! mountpoint "$BACKUP_SOURCE_DEV"; then
echo "$(date "+%Y-%m-%d %k:%M:%S") - ERROR: Backup source device is not mounted!" >> "$LOG_FILE"
end 1
fi
# Check that source dir exists and is readable.
if [ ! -r "$BACKUP_SOURCE" ]; then
echo "$(date "+%Y-%m-%d %k:%M:%S") - ERROR: Unable to read source dir." >> "$LOG_FILE"
echo "$(date "+%Y-%m-%d %k:%M:%S") - ERROR: Unable to sync." >> "$LOG_FILE"
end 1
fi
# Check that target dir exists and is writable.
if [ ! -w "$BACKUP_TARGET" ]; then
echo "$(date "+%Y-%m-%d %k:%M:%S") - ERROR: Unable to write to target dir." >> "$LOG_FILE"
echo "$(date "+%Y-%m-%d %k:%M:%S") - ERROR: Unable to sync." >> "$LOG_FILE"
end 1
fi
# Check if the drive is mounted
if ! mountpoint "$BACKUP_TARGET_DEV"; then
echo "$(date "+%Y-%m-%d %k:%M:%S") - WARNING: Backup device needs mounting!" >> "$LOG_FILE"
# If not, mount the drive
if mount "$BACKUP_TARGET_DEV" > /dev/null 2>&1 || /bin/false; then
echo "$(date "+%Y-%m-%d %k:%M:%S") - Backup device mounted." >> "$LOG_FILE"
else
echo "$(date "+%Y-%m-%d %k:%M:%S") - ERROR: Unable to mount backup device." >> "$LOG_FILE"
echo "$(date "+%Y-%m-%d %k:%M:%S") - ERROR: Unable to sync." >> "$LOG_FILE"
end 1
fi
fi
# Start entry in the log
echo "$(date "+%Y-%m-%d %k:%M:%S") - Sync started." >> "$LOG_FILE"
# Start sync
su -c "rsync -ayhEAX --progress --delete-after --inplace --compress-level=0 --log-file=\"$LOG_FILE\" \"$BACKUP_SOURCE\" \"$BACKUP_TARGET\"" $USER
echo "" >> "$LOG_FILE"
# Unmount the drive so it does not accidentally get damaged or wiped
if umount "$BACKUP_TARGET_DEV" > /dev/null 2>&1 || /bin/false; then
echo "$(date "+%Y-%m-%d %k:%M:%S") - Backup device unmounted." >> "$LOG_FILE"
else
echo "$(date "+%Y-%m-%d %k:%M:%S") - WARNING: Backup device could not be unmounted." >> "$LOG_FILE"
fi
# Exit successfully
end 0
I am skimming This but I would think you would rather rsync -e ssh and setup the keys to accept the account.
Related
For some reason commands are not running after the first if statement.
"/usr/local//backup.sh: sleep: not found" for example..
The first if statement goes like:
if [ "$command" == "start -c" ]; then
echo -e "${ORANGE}Starting website backup...${E}"
sleep 1
DT=`date +%Y-%m-%d`
echo -e "${ORANGE}Started backup at $DT ${E}"
sleep 1
tar -zcvf web-$DT.tar.gz /usr/local/www/nginx
echo -e "${ORANGE}Compatced files, moving to backup directory${E}"
sleep 1
mv web-$DT.tar.gz $PATH/web-$DT.tar.gz
echo -e "${CYAN}Moved to backups ($PATH/web-$DT.tar.gz)\nDo you want to upload to ftp?${E}\n${CYAN} 'y' or 'n'?${E}"
read answer
if [ "$answer" == "y" ]; then
echo -e "${ORANGE}Uploading to ftp server...${E}"
sleep 1
if ftp -in -u ftp://$USER:$PASS#$HOST/Backups/f $PATH/web-$DT.tar.gz; then
echo -e "${GREEN}Uploaded! Bye!${E}"
else
echo -e "${ORANGE}Couldn't upload with ftp command, trying with curl...${E}"
sleep 1
curl -T "$PATH/web-$DT.tar.gz" -u $USER:$PASS ftp://$HOST/Backups/f/
echo -e "${GREEN}Uploaded! Bye!${E}"
fi
else
echo -e "${GREEN}Bye!${E}"
fi
Everything works fine inside this statement, however, after the elif compassion it just doesn't.
Here's the problematic code:
elif [ "$command" == "start -d" ]; then
echo -e "${ORANGE}Starting database backup...${E}"
sleep 1
DT=`date +%Y-%m-%d`
echo -e "${ORANGE}Started backup at $DT ${E}"
sleep 1
umask 177
echo -e "${ORANGE}Dumping database 'account'\n${E}"
mysqldump --user=$DBUSER --password=$DBPASS --host=$HOST account > $PATH/account-$DT.sql
sleep 1
echo -e "${ORANGE}Dumping database 'game'\n${E}"
mysqldump --user=$DBUSER --password=$DBPASS --host=$HOST game > $PATH/game-$DT.sql
sleep 1
echo -e "${ORANGE}Dumping database 'forum'\n${E}"
mysqldump --user=$DBUSER --password=$DBPASS --host=$HOST forum > $PATH/forum-$DT.sql
sleep 1
echo -e "${CYAN}Moved to backups ($PATH/<database-date>.sql)\nDo you want to upload to ftp?${E}\n${CYAN} 'y' or 'n'?${E}"
read answer
if [ "$answer" == "y" ]; then
echo -e "${ORANGE}Uploading to ftp server...${E}"
sleep 1
curl -T "$PATH/account-$DT.sql" -u $USER:$PASS ftp://$HOST/Backups/f/Databases/
curl -T "$PATH/game-$DT.sql" -u $USER:$PASS ftp://$HOST/Backups/f/Databases/
curl -T "$PATH/forum-$DT.sql" -u $USER:$PASS ftp://$HOST/Backups/f/Databases/
sleep 1
echo -e "${GREEN}Uploaded! Bye!${E}"
else
echo -e "${GREEN}Bye!${E}"
fi
and then I just ended it..
else
echo -e "${RED}Sorry! Not found${E}"
fi
As you can see there's spaces in the if statements and all of that, so what's wrong with this??
I've the #!/bin/bash up top as well, all the variables exist too.
You seem to have overwritten the value of the PATH variable at some point in your code. The shell needs that variable in order to know where to find programs like sleep (Hence the "not found" error). Name your path variable something else.
Im somewhat beginner in bash scripting. I have here part of script that uploades files to sftp server. Then it shoud move files to other directory.
Else echo info about no files in source_dir. Problem is that its not moving files and is looping back to sftp login after files are already uploaded.
cd /dest_dir/
for file5 in *.test
do
if test -f $file5
then
echo 'some text.'
((
echo "
cd /dest_dir/
lcd /source_dir/
mput *.test
exit
"
) | sftp "user"#"host")
sleep 3
mv /source_dir/$file5 /source_dir/test/
else
echo -e 'some text'
fi
There is normally no reason to check that the files you are looping over actually exist. If a file could disappear between the for and the test, it could just as well disappear between the test and the echo instead, in which case you end up referring to a file which no longer exists anyway.
#!/bin/bash
shopt -s nullglob # bash-only feature
cd /dest_dir/
(#echo "cd /dest_dir/" # no use, you already did above
echo "lcd /source_dir/"
for file in *.test; do
echo put "$file"
done
echo "exit" ) | sftp "user"#"host"
mv *.test /source_dir/test/
This opens a single scp connection for all the files. It has the distinct disadvantage that if one of the files fails for some reason, the script doesn't catch that.
Apart from the shopt -s nullglob this should be portable to Bourne shell in general.
thank you for tips. I made it: with loging:
SFTP_HOST="host"
SFTP_LOGIN="USER"
cd /path/
mylog=/path/sftp_session_$(date "+%Y_%m_%d").log
echo "$(date "+%Y-%m-%d %H:%M:%S") - text" >> $mylog
let licz5=`ls|wc -l`
let jest_plik=0
for file5 in *.test
do
if test -f /patch_source1/$file5
then
let jest_plik=1
echo "$(date "+%H:%M:%S") - transfer pliku "$file5" na serwer "$SFTP_HOST >> $mylog
fi
if test -f /source_patch2/$file6
then
echo "$(date "+%H:%M:%S") - transfer pliku "$file6" na serwer "$SFTP_HOST >> $mylog
fi
if test -f /source_patch3/$file7
then
echo "$(date "+%H:%M:%S") - transfer pliku "$file7" na serwer "$SFTP_HOST >> $mylog
fi
if test -f /source_patch4/$file8
then
echo "$(date "+%H:%M:%S") - transfer pliku "$file8" na serwer "$SFTP_HOST >> $mylog
fi
done
if test $jest_plik -eq 1
then
echo 'text.'
(echo 'cd /dest_dir/
lcd /source_p_1/
mput *.test
lcd /source_p_2/
mput *.test
lcd /source_p_3/
mput *.test
lcd /source_p_4/
mput *.test
exit') | sftp $SFTP_LOGIN#$SFTP_HOST
echo "$(date "+%H:%M:%S") - send ok." >> $mylog
else
echo -e 'text'
fi
I wrote a script in bash (a neophyte) that creates a file on the local flash drive and writes random data on it until it fills up. It then copies the file to an external usb drive and deletes the local file. Once the file has been filled up and it is on the usb drive, it is copied back to the local NAND flash, deleted, and copied from the usb flash drive again (indefinitely, until the user stops it or an error occurrs, whichever is first - this is in a while loop). When I run the script it displays:
nand_test.sh: line 19: /tmp/activity.log: Text file busy
nand_test.sh: line 19: /tmp/activity.log: Text file busy
nand_test.sh: line 19: /tmp/activity.log: Text file busy
nand_test.sh: line 19: /tmp/activity.log: Text file busy
and just hangs there. Can someone tell me if there are errors in my script? I'm very green when it comes to bash. Below is the code:
LOG="/tmp/activity.log"
function if_error
{
if [[ $? -ne 0 ]]
then
print "$1 TIME:$TIME" | tee -a $LOG
exit $?
fi
}
#whenever the echo command is ran this function allows me add a timestamp
function echo {
/bin/echo `date` $* | $LOG
}
#condition below checks if activity.log exists. If not, it creates it.
mydir="/media/myusb"
chmod +x /tmp/activity.log
activity="/tmp/activity.log"
if [ -e "$activity" ];then
echo - "$activity" LOG ALREADY EXISTS >> "$activity"
else
> /activity.log
#echo - "$activity" LOG HAS BEEN CREATED >> "$activity"
fi
#condition below checks if myusb directory is created. If not, it creates it.
if [ -d "$mydir" ];then
echo - "$mydir" ALREADY EXISTS >> "$activity"
else
mkdir /media/myusb
#echo - "$mydir" HAS BEEN CREATED >> "$activity"
fi
#check if external usb has been mounted. if not mount it.
device0="/dev/sda1"
if [ -b "$device0" ];then
echo - "$device0" IS ALREADY MOUNTED >> "$activity"
else
mount LABEL=MYFLASH /media/myusb
#echo - "$device0" HAS BEEN MOUNTED >> "$activity"
fi
#condition below checks if testfile.txt has been created. If not, it creates it.
testfile="/storage/testfile.txt"
if [ -e "$testfile" ];then
echo - "$testfile" FILE ALREADY EXISTS >> "$activity"
else
>> /storage/testfile.txt
#echo - "$testfile" HAS BEEN CREATED! >> "$activity"
fi
dd if=/dev/urandom of=/storage/testfile.txt >> "$activity"
ret=$?
if_error "urandom data failed writing to testfile.txt"
if [ "$ret" gt 0 ];then
echo - "NAND FLASH DATA TEST FAILED >> "$activity"
else
cp "$testfile" "$mydir"
fi
rm "$testfile"
sync
sleep 3
while [ -e "/media/myusb/testfile.txt" ]
do
cp /media/myusb/testfile.txt /storage
sync
DIFF= diff /media/myusb/testfile.txt "$testfile"
if [ "$DIFF" != "" ];then
echo - "ERROR: THE FILE HAS BEEN MODIFIED" >> "$activity"
else
echo - "FILE COMPARISON SUCCESSFUL" >> "$activity"
fi
rm "$testfile"
sync
You have this line at the top:
LOG="/tmp/activity.log"
and then:
/bin/echo `date` $* | $LOG
It doesn't make sense since you need to have a valid Unix command after pipe not just the file name.
A little history behind this - I'm trying to write a nagios plugin to detect if an nfs mount is unmounted and if a mount is stale, which is where I'm running into a problem.
What I'm trying to achieve is detecting if a mount is stale. The problem I'm trying to work around is the fact that a stale nfs handle causes any action on that directory to hang and timeout after 3-4 minutes. By forcing a timeout onto a stat command inside an nfs mounted directory with read, I should be able to work around that problem.
So I picked up this snippet somewhere, which works perfectly when run manually from the cli on an nfs client (where /www/logs/foo is a stale nfs mount)
$ read -t 2 < <(stat -t /www/logs/foo/*); echo $?
1
The problem comes when I try to incorporate this snippet into a script like so (snippet attached, full script attached at the end):
list_of_mounts=$(grep nfs /etc/fstab | grep -v ^# | awk '{print $2'} | xargs)
exitstatus $LINENO
for X in $list_of_mounts; do
AM_I_EXCLUDED=`echo " $* " | grep " $X " -q; echo $?`
if [ "$AM_I_EXCLUDED" -eq "0" ]; then
echo "" >> /dev/null
#check to see if mount is mounted according to /proc/mounts
elif [ ! `grep --quiet "$X " /proc/mounts; echo $?` -eq 0 ]; then
#mount is not mounted at all, add to list to remount
remount_list=`echo $remount_list $X`;
#now make sure its not stale
elif [ ! "`read -t 2 < <(stat -t $X/*) ; echo $?`" -eq "0" ]; then
stalemount_list=`echo $stalemount_list $X`
fi
Gives me this error:
/usr/lib64/nagios/plugins/check_nfs_mounts.sh: command substitution: line 46: syntax error near unexpected token `<'
/usr/lib64/nagios/plugins/check_nfs_mounts.sh: command substitution: line 46: `read -t 2 < <( '
/usr/lib64/nagios/plugins/check_nfs_mounts.sh: command substitution: line 46: syntax error near unexpected token `)'
/usr/lib64/nagios/plugins/check_nfs_mounts.sh: command substitution: line 46: ` ) ; echo $?'
/usr/lib64/nagios/plugins/check_nfs_mounts.sh: line 46: [: stat -t /www/logs/foo/*: integer expression expected
I was able to work around the syntax error by using " read -t 2<<< $(stat -t $X/)" instead of " read -t 2< <(stat -t $X/)", however stat no longer benefits from the timeout on read, which takes me back to the original problem.
While I'm open to new solutions, I'm also curious as to what behavior might be causing this shell vs script difference.
Full nagios check:
#!/bin/bash
usage() {
echo "
Usage:
check_nfs_mounts.sh
It just works.
Optional: include an argument to exclude that mount point
"
}
ok() {
echo "OK - $*"; exit 0
exit
}
warning() {
echo "WARNING - $*"; exit 1
exit
}
critical() {
echo "CRITICAL - $*"; exit 2
exit
}
unknown() {
echo "UNKNOWN - $*"; exit 3
exit
}
exitstatus() {
if [ ! "$?" -eq "0" ] ;
then unknown "Plugin failure - exit code not OK - error line $*"
fi
}
# Get Mounts
list_of_mounts=$(grep nfs /etc/fstab | grep -v ^# | awk '{print $2'} | xargs)
exitstatus $LINENO
for X in $list_of_mounts; do
AM_I_EXCLUDED=`echo " $* " | grep " $X " -q; echo $?`
if [ "$AM_I_EXCLUDED" -eq "0" ]; then
echo "" >> /dev/null
#check to see if mount is mounted according to /proc/mounts
elif [ ! `grep --quiet "$X " /proc/mounts; echo $?` -eq 0 ]; then
#mount is not mounted at all, add to list to remount
remount_list=`echo $remount_list $X`;
#now make sure its not stale
elif [ ! "`read -t 2 <<< $(stat -t $X/*) ; echo $?`" -eq "0" ]; then
stalemount_list=`echo $stalemount_list $X`
fi
done
#Make sure result is a number
if [ -n "$remount_list" ] && [ -n "$stalemount_list" ]; then
critical "Not mounted: $remount_list , Stale mounts: $stalemount_list"
elif [ -n "$remount_list" ] && [ -z "$stalemount_list"]; then
critical "Not mounted: $remount_list"
elif [ -n "$stalemount_list" ] && [ -n "$remount_list" ]; then
critical "Stale mount: $stalemount_list"
elif [ -z "$stalemount_list" ] && [ -z "$remount_list" ]; then
ok "All mounts mounted"
fi
You need to make sure your shebang specifies Bash:
#!/bin/bash
The reason for the error message is that on your system, Bash is symlinked to /bin/sh which is used when there's no shebang or when it's #!/bin/sh.
In this case, Bash is run as if you had started it with bash --posix which disables some non-POSIX features such as process substitution (<()), but confusingly not others such as here strings (<<<).
Change your shebang and you should be OK.
You can save the output of a subshell in this way:
$ read a < <(echo one)
$ echo $a
one
Or in this way (if you just want to process $a and forget it:
$ ( echo one; echo two) | (read a; echo $a)
one
The first variant will work only in bash. Bourne Shell (/bin/sh) does not support this syntax. May be that is the reason why you get the error message. May be you script is interpreted by /bin/sh not by /bin/bash
notice the FTP_PUT_RETVAL. There are two echo commands, the first one shows a value of '0'. The second one shows no value at all. I am running this inside a nightly cron. BASH is GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)
My script tells me that the ftp upload was unsuccessful, because FTP_PUT_RETVAL contains no value!
Why is this occuring? How can I change this? What have I done wrong?
#!/bin/sh
#
# Filename: rh5-manager-cron.sh
#
# Purpose: Runs backup.cron, and FTP uploads backup to Linux4
#
# Usage: the program is run with no arguments. This program is
# intended to run from manager cron, and redirection is handled inside the cron
# e.g. 00 1 * * * /u2/app/lbin/rh5-manager-cron.sh > /tmp/log/rh5-manager-cron.log 2>&1
trap signalCaught ABRT EXIT HUP INT PIPE TERM QUIT
signalCaught () {
for file in $FTP_LOG_FILE $TMPF; do
$BIN_HOME/rm_file $TMPF
done
exit
}
if [[ ! -r /u2/conf/ctrl/lettus.sh || ! -r /u2/app/lbin/fsh_sh_lib ]]; then
printf "Cannot source environment.\n" >&2
exit 1
fi
. /u2/conf/ctrl/lettus.sh
. /u2/app/lbin/fsh_sh_lib
#-------------------------------------------------------
# Variables
#-------------------------------------------------------
PRG=${0##*/}
FTPUSER=dummy
FTPPASS=dummy
FTPHOST=192.168.0.3
BACKUPDIR=/backup
FTPBACKUPNAME=Redhat5Backup.tgz
FTPBACKUPFILE=$BACKUPDIR/$FTPBACKUPNAME
LOGDIR=/tmp/log
FTP_LOG_FILE=$LOGDIR/Redhat5FTP.log
SENDLOGS=$C/sendlogs.dat
ZOOT_XML=$C/zoot.xml
TMPF=`mktemp` || exit 1
#-------------------------------------------------------
# Sanity
#-------------------------------------------------------
if ! isValidUser root manager; then
printf "$PRG: Must be run as user 'root' or user 'manager'.\n" >&2
exit 1
fi
if [[ ! -d $BACKUPDIR ]]; then
logger "$PRG: $BACKUPDIR: Not a valid directory" >&2
exit 1
fi
if [[ ! -d $LOGDIR ]]; then
logger "$PRG: $LOGDIR: Not a valid directory" >&2
exit 1
fi
if [[ ! -r $SENDLOGS || ! -r $ZOOT_XML ]]; then
logger "$PRG: E-mail: Files are not readable: $SENDLOGS, $ZOOT_XML" >&2
exit 1
fi
if ! which lftp >/dev/null 2>&1; then
logger "$PRG: lftp: command not found" >&2
exit 1
fi
# e-mail
EMAIL_SUBJECT="Redhat5 FTP PUT"
EMAIL_TO=$(email_to $SENDLOGS)
EMAIL_FROM=$(email_from $ZOOT_XML)
# ftp binary
LFTP_BIN=$(which lftp 2>/dev/null)
#-------------------------------------------------------
# Functions
#-------------------------------------------------------
# calls lftp to upload a file to server non-interactively
ftp_put() {
$LFTP_BIN $LFTP_DEBUG -u ${FTPUSER},${FTPPASS} $FTPHOST <<-EOF
put $FTPBACKUPFILE
pwd
ls $FTPBACKUPNAME
quit
EOF
#^^^^^^^^^^^ leave the above indentation alone
}
main() {
# Backup, and send manager logs
logger "Running backup.cron..."
echo
backup.cron
BACKUP_CRON_RETVAL=$?
logger "Running fsh_sendlogs..."
echo
$SH_HOME/fsh_sendlogs 1
# show ls listing
logger "Here comes a directory listing..."
echo
/bin/ls -l /backup/Redhat5Backup.tgz
echo
# ftp upload
logger "Running ftp upload..."
echo
ftp_put
FTP_PUT_RETVAL=$?
echo " -- debug: Line ${LINENO:-}: FTP_PUT_RETVAL=${FTP_PUT_RETVAL:-}"
}
checkSuccess() {
if [[ "$BACKUP_CRON_RETVAL" -eq 0 ]]; then
echo "Backup was successful."
echo
echo "*********************************"
echo " OK: Backup was successful."
echo "*********************************"
echo
else
echo "ERROR: Backup FAILED! "
echo
echo "*********************************"
echo " ERROR: Backup FAILED! "
echo "*********************************"
echo
fi
echo " -- debug: Line ${LINENO:-}: FTP_PUT_RETVAL=${FTP_PUT_RETVAL:-}"
if [ "$FTP_PUT_RETVAL" -eq 0 ]; then
echo "lftp: ftp file upload complete."
echo
echo "*********************************"
echo " OK: ftp file upload complete."
echo "*********************************"
echo
else
echo "lftp: error ftp file upload not successful."
echo
echo "*********************************"
echo " ERROR: file upload"
echo " NOT successful."
echo "*********************************"
echo
fi
}
email_logs() {
if [[ -z "$EMAIL_FROM" || -z $EMAIL_TO || -z $EMAIL_SUBJECT || ! -r $FTP_LOG_FILE ]]; then
logger "$PRG: One of the variables is not correctly configured" >&2
exit 1
fi
fsh_mail -r "${EMAIL_TO}" -F "${EMAIL_FROM}" -s "${EMAIL_SUBJECT}" -t "${FTP_LOG_FILE}"
return
}
#----------------------------------------------------------------------
# Main Program
#----------------------------------------------------------------------
main | tee $FTP_LOG_FILE
checkSuccess | tee -a $FTP_LOG_FILE $TMPF
cat $FTP_LOG_FILE >> $TMPF
# E-mail ftp log file
logger "Emailing ftp logfile"
echo
email_logs
#eof
The problem is that you are using:
main | tee $FTP_LOG_FILE
checkSuccess | tee -a $FTP_LOG_FILE $TMPF
Because of the piping, the work done in main is done in a sub-shell, and a sub-shell cannot set variables in the parent shell. So, when checkSuccess (which is also run in a sub-shell) goes to look at the results, it sees what was in the parent shell (nothing), rather than what was set in the main function in a sub-shell.
If you dropped the piping, it would start to work.
More reliably, put the call to checkSuccess into the main function. Or use one or the other of these two notations:
{ main; checkSuccess; } | tee $FTP_LOG_FILE $TMPF
( main; checkSuccess ) | tee $FTP_LOG_FILE $TMPF
Note that the { ... } notation requires a semi-colon after the second function which the ( ... ) notation does not require. However, there is one less process involved in the { ... } mechanism, not that it is going to make any measurable difference to the overall performance of this (the FTP time will dominate).