Need some shell scripting help, especially with my if-then-else
logic. I want to combine both conditions, but not sure if the file checks will work the same? Should I be doing something like a nested if?? My script uses the if
statements to do file checks to see if they exist, then do something..
There is probably a better way to do file checks part too.
Any help, critique would be appreciated. Thanks.
Here's my code, it sort of works.
if [ $# != 1 ]; then
echo "Usage: getlogs.sh <remote-host>" 2>&1
exit 1
fi
#Declare variables
STAMP=`date '+%Y%m%d-%H:%M'`
REMOTE_MYCNF=/var/log/mysoft/mysoft.log
REMOTE_GZ=/var/log/mysoft/mysoft.log.1.gz
REMOTE_DIR=/var/log/mysoft/
BACKUP_DIR=/home/mysql/dev/logs/
NEWLOG="foo-temp.log"
export REMOTE_MYCNF STAMP SHORTNAME
export REMOTE_DIR REMOTE_GZ
#Copy file over
echo "START..." 2>&1
test -f $BACKUP_DIR$1.mysoft.log
if [ $? = 0 ]; then
echo "Local log file exists, clean up for new copy..." 2>&1
/bin/rm $BACKUP_DIR$1.mysoft.log
exit 0
else
echo "File does not exist, getting a new copy..." 2>&1
fi
echo "Checking remotely in $1 for foo logfile $REMOTE_MYCNF $STAMP" 2>&1
if [ ! -f $REMOTE_MYCNF ]; then
echo "File exists remotely, creating new logfile and copy here...." 2>&1
ssh $1 "zcat $REMOTE_GZ >> $REMOTE_DIR$NEWLOG"
ssh $1 "cat $REMOTE_MYCNF >> $REMOTE_DIR$NEWLOG"
/usr/bin/scp $1:$REMOTE_DIR$NEWLOG $BACKUP_DIR$1.mysoft.log
echo "end remote copy" 2>&1
echo "Cleaning up remote files" 2>&1
ssh $1 "rm $REMOTE_DIR$NEWLOG"
exit 0
else
echo "Unable to get file" 2>&1
exit 0
fi
Updated code using help:
if [ -f $BACKUP_DIR$1.mysoft.log ]; then
echo "Local log file exists, clean up for new copy..." 2>&1
/bin/rm $BACKUP_DIR$1.mysoft.log
exit 0
else
echo "File does not exist, getting a new copy..." 2>&1
echo "Checking remotely in $1 for foo logfile $REMOTE_MYCNF $STAMP" 2>&1
if [ ! -f $REMOTE_MYCNF ]; then
echo "File exists remotely, creating new logfile and bring a copy here...." 2>&1
ssh $1 "zcat $REMOTE_GZ >> $REMOTE_DIR$NEWLOG"
ssh $1 "cat $REMOTE_MYCNF >> $REMOTE_DIR$NEWLOG"
/usr/bin/scp $1:$REMOTE_DIR$NEWLOG $BACKUP_DIR$1.mysoft.log
echo "end remote copy" 2>&1
echo "Cleaning up remote files" 2>&1
ssh $1 "rm $REMOTE_DIR$NEWLOG"
exit 0
else
echo "Unable to get file" 2>&1
exit 0
fi
fi