Hi,
if [ 'grep notice $file' ]
then
mailx -s " MESSAGE " abc@xyz.com < $file
else
exit
fi
Could you let me know if the pattern is not found will the script exit.
Hi,
if [ 'grep notice $file' ]
then
mailx -s " MESSAGE " abc@xyz.com < $file
else
exit
fi
Could you let me know if the pattern is not found will the script exit.
Please can you elaborate the variables used in the script.
Cheers,
Shazin
Hi Shazin,
We need to grep for a pattern from a given file, if the pattern is found we need to mail to an address. Else the script should quit.
if [ 'grep notice /export/home/test/test.log' ]
then
mailx -s " MESSAGE " abc@xyz.com < /export/home/test/test.log
else
exit
fi
try to capture the return code of grep..
grep -q "notice" $file
if [ $? -ne 0 ] ; then
exit
else
mailx -s " MESSAGE " abc@xyz.com < $file
fi
Plan B
FILE=/export/home/test/test.log
if [ -z "$( grep 'notice' $FILE )" ]
then
exit 1
fi
mailx -s " MESSAGE " abc@xyz.com < $FILE
exit 0
Thanks dr.house, it worked.
Hi,
Youo can also use the below scripts :
grep notice $file
if [ $? -eq 0 ] ; then
mailx -s " MESSAGE " abc@xyz.com < $file
else
exit
fi
Sorry for late reply
Best Regards,
Shazin
( grep 'notice' a.txt ) && mail -s "MESSAGE" abc@xyz.com < a.txt
[ is test command, not bracket. Shell script syntax look like some programming language, but it's only group of command lines. if test next commands exit status. So we don't need to test exit code using [, because if do it.
if syntax is:
if commandlist
then
# do this commandlines if exit status is 0 in the last command in command list
else
# exit status is not 0, do this commandlines
fi
Solution after those data:
# no need to echo grep output
# if grep exit code is 0 then mailx, else exit
if grep notice $file >/dev/null 2>&1
then
mailx -s " MESSAGE " abc@xyz.com < $file
else
exit 1 # only example, if not ok, exit with some not 0 value
fi
Or if not grep then exit
if ! grep notice $file >/dev/null 2>&1
then
exit 1
fi
mailx -s " MESSAGE " abc@xyz.com < $file
We can write it shortly without if-then-else like shantanuo has done.
grep some >/dev/null 2>&1 && mailx
#or
grep some >/dev/null 2>&1 || exit 1
mailx
&& = if previous command exit code is 0, then do next
|| = if previous command exit code is not 0, then do next