If condition

here is my script
########
#! /bin/sh
export PATH=$PATH:/opt/mysql/bin/
#echo $PATH
echo $LD_LIBRARY_PATH
USER="root"
PASS="xyz"
DB="sme"
DATE=$(date +%d%b%y_%k.%M.%S)
#DATE=`date +%y-%d-%m`
if
mysqldump -u $USER -p$PASS $DB | gzip -9>/home/backup1/today_sme-$DATE.sql.gz
then
find /home/backup1 -mtime +0 -exec rm -f {} \;
echo "done"
else
echo "not done"
fi
########

I want If mysqldump -u $USER -p$PASS $DB | gzip -9>/home/backup1/today_sme-$DATE.sql.gz
executes successfully then only
find /home/backup1 -mtime +0 -exec rm -f {} \;
execute
else echo "not done" execute

Actually this is a pipeline consisting of two components (mysqldump and gzip). The success of this pipeline depends in the success of the two programs; either mysqldump may fail or gzip (or both ofcourse). It's better to rewrite these lines as follows:

set -o pipefail
mysqldump -u $USER -p$PASS $DB | gzip -9>/home/backup1/today_sme-$DATE.sql.gz
if [ $? -ne 0 ]; then
    blabla
else
    blabla
fi

The pipefail bash option is controlling the exit status of a pipeline (read the manual pages for bash). Of course the two components must be written correctly from their authors (exiting with non zero exit statuses when failures occur).

I changes my script as follow

############################################################
#! /bin/sh
export PATH=$PATH:/opt/mysql/bin/
#echo $PATH
echo $LD_LIBRARY_PATH
USER="root"
PASS="XYZ"
DB="sme"
DATE=$(date +%d%b%y_%k.%M.%S)
#DATE=`date +%y-%d-%m'
set -o pipefail
mysqldump -u $USER -p$PASS $DB | gzip -9>/home/backup1/today_sme-$DATE.sql.gz;
if[$? -ne 0]; then
find /home/backup1/ -mtime +4 -exec rm -f {} \;
exit 0
else
echo "done"
exit 1
fi

#############################################################

but while executing it shows error

bck_script.sh: line 19: syntax error near unexpected token `then'
bck_script.sh: line 19: `if[$? -ne 0]; then '

You must use spaces in brackets:

if [ $? -ne 0 ]; then

Thanks

Leave a space after between if and bracket too!

if [ $? -ne 0 ]; then

I changes

set -o pipefail
ysqldump -u $USER -p$PASS $DB | gzip -9>/home/backup1/today_sme-$DATE.sql.gz;
if [ $? -ne 0 ]; then
echo "done"
find /home/backup1/ -mtime +4 -exec rm -f {} \;
exit 0
else
echo "not done"
exit 1
fi

still it executes done while mysqldump(which changes to sqldump for test purpose) not executing

Are you sure that the mysqldump program exits with non xero value where things go wrong?

Yes Mysqldump is kind enough to use non-zero ones on any kind of error

just echo the $? value to a variable and see whether the value is non zero or not!!

var1=$?

Thanks to you all

var1=0 if done successfully
var1=2 if not done

finally problem is solved

when i changed if [ "$?" == "0" ]; instead of if [ $? -ne 0 ]; then
this script gives output as required