Bash Script Send Email If Error
Contents |
Start here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow the company Business Learn more about shell script trap hiring developers or posting ads with us Server Fault Questions Tags Users Badges Unanswered Ask Question shell script error handling _ Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute: Sign up Here's shell script to monitor log file for errors how it works: Anybody can ask a question Anybody can answer The best answers are voted up and rise to the top bash script alert on error up vote 3 down vote favorite 3 I've a script which do. bash send mail ls , cp, mv I want if any of the command fail this should alert over email as well as after successful competition. Any idea? I can adjust email alert but want to know how to check for errors and successful attempt. linux bash scripting share|improve this question asked Mar 27 '11 at 18:45 User4283 4622519 Looks like you want to keep track of access to your server. This is not the best way to set restrictions
Bash Trap Error
or logging. An alternative for ls would be find -maxdepth 1 -ls, mv/cp could be replaced by a python/perl script or a combination with tar. Of course, it's possible to place your own binaries on the system and execute them. What would you like to accomplish? –Lekensteyn Mar 27 '11 at 19:50 add a comment| 4 Answers 4 active oldest votes up vote 1 down vote accepted You can have a series of commands continue to execute until "failure" by using "&&" to run the commands in succession; each command returns "true", causing the following command to run. Then use "||" to run a command upon failure, such as: #!/bin/bash cp foo bar \ && mv bar bar{,.bak} \ && echo "good so far" \ && ls file123 | tee -a /tmp/msg.txt \ && mailx -u user -s "success" -f /tmp/msg.txt \ || mailx -u user -s "failure" -f ~/err.txt Since that can get messy, use functions, such as #!/bin/bash do_work() { mv... || return 1 cp... || return 1 return 0 } report() { [ "$1" = "ok" ] && mailx .... [ "$1" != "ok" ] && mailx -s "$1" .... return 0 } do_work \ && report ok || report err Further, continuing from the above example, you can add blanket rules via a 'trap' in the script that will always execute certain commands if any type of error status is returned
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow the company Business Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; http://serverfault.com/questions/252448/bash-script-alert-on-error it only takes a minute: Sign up Capturing and mailing bash script errors up vote 3 down vote favorite I have a script that I run nightly in cron to backup some postgres databases for several hosts on my network. I have a way of getting alerted that the script fails by leveraging the exit status, but it doesn't http://stackoverflow.com/questions/6784295/capturing-and-mailing-bash-script-errors tell me WHY it failed. Based off the following code, how can I capture any errors that occur when the script is run, and email them to me so I can have a better understanding of what happened. FILEDATE=`date '+%Y-%m-%d'` BASEDIR=/u1/$1/db_dumps PGDUMP=/path/to/pg_dump HOST=$1 DB=$2 if [ $DB == all ] then for ALLDUMPS in db1 db2 db3 do ssh root@$HOST "env PGUSER=pguser PGPASSWORD=pgpassword $PGDUMP -Fc $ALLDUMPS" | pbzip2 > $BASEDIR/$FILEDATE-$HOST-$ALLDUMPS.dump.bz2 if [ $? -ne 0 ] then mutt -s "dbdumper could not create a backup of $ALLDUMP from $HOST" me@myemail.com < /dev/null fi done else ssh root@$HOST "env PGUSER=pguser PGPASSWORD=pgpassword $PGDUMP -Fc $DB" | pbzip2 > $BASEDIR/$FILEDATE-$HOST-$DB.dump.bz2 if [ $? -ne 0 ] then mutt -s "dbdumper failed to create a backup of $DB from $HOST" me@myemail.com < /dev/null fi fi email bash stderr share|improve this question asked Jul 22 '11 at 0:03 Joseph 162 add a comment| 1 Answer 1 active oldest votes up vote 2 down vote Capture stderr from the ssh command, and email that to yourself. stderr=$( ssh root@$HOST "env PGUSER=user PGPASSWORD=pw $PGDUM
1 #1 2011-05-26 09:40:02 daJense Member Registered: 2009-05-17 Posts: 45 Bash script - send mail only if script causes an error Hi,I have a script https://bbs.archlinux.org/viewtopic.php?id=119721 running on a server for backup purposes. I use/bin/mail -s "$SUBJECT" "$EMAIL" http://broexperts.com/how-to-send-email-notification-upon-success-or-failure-of-bash-script/ < $EMAILMESSAGE to send a report at the end of the script. But I would like it to send the report only if the script errors out.Any ideas,Thx Offline #2 2011-05-26 09:46:25 Damnshock Member From: Barcelona Registered: 2006-09-13 Posts: 414 Re: Bash script - send mail shell script only if script causes an error That depends on how you capture errors and how you call the script you are running. If you don't "exit" on errors, at least set a variable like "error" and, at the end of your script use something like:if [[ error ]] ; then /bin/mail -s "$SUBJECT" "$EMAIL" < $EMAILMESSAGEfi My blog: bash script send blog.marcdeop.comJabber ID: damnshock@jabber.org Offline #3 2011-05-26 10:03:15 daJense Member Registered: 2009-05-17 Posts: 45 Re: Bash script - send mail only if script causes an error Thanks, I will try setting the variable. Btw the script is being called by another bashscript executing via cron on another server. Offline #4 2011-05-27 04:13:49 anrxc Member From: Croatia Registered: 2008-03-22 Posts: 834 Website Re: Bash script - send mail only if script causes an error heirloom-mailx (new default mailx in Arch) supports -E, it won't send an e-mail if the body is empty. Good for cron. You need to install an RTFM interface. Offline #5 2011-05-27 20:28:36 briest Member From: Katowice, PL Registered: 2006-05-04 Posts: 468 Re: Bash script - send mail only if script causes an error Bash (and probably other shells) has builtin command "trap" -- maybe you'd find it useful. Offline Pages: 1 Index »Networking, Server, and Protection »Bash script - send mail only if script causes an error Board footer Jump to Newbie Corner Installation Kernel & Hardware Applications & Desktop Environ
Failure of Bash ScriptIn this guide we are going to look at some questions asked by our readers, which is related to handling errors notifications during the execution of shell script. A good shell script must have ability to notify the situation if something goes wrong. Readers questions on our previous article : How to Backup files and Directories in Linux Using Tar & Cron Jobs.SOLUTIONTo accomplished this task we will configure Postfix (Postfix is a free, open-source, heavily maintained and secure mail transfer agent) as a relay through Gmail and then modify our bash script to receive success or failure result, via email.LAB RequirementsCentOS 7.x / Red Hat Enterprise Linux 7.xValid Gmail AccountInstallation of Required Softwares:We are installing Postfix as MTA (Mail Transfer Agent) and mailx (which is command line email sending program) so that we can send email notification using bash script.# yum install postfix mailx cyrus-sasl-plain cyrus-sasl -yPostfix ConfigurationConfigure Postfix by adding below lines at the end of /etc/postfix/main.cf file.# vi /etc/postfix/main.cfAdd below lines at the end of main.cf file.relayhost = [smtp.gmail.com]:587 smtp_sasl_auth_enable = yes smtp_use_tls = yes smtp_tls_CAfile = /etc/ssl/certs/ca-bundle.crt smtp_sasl_security_options = noanonymous smtp_sasl_tls_security_options = noanonymous smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwdSave & Exit.configure Postfix SASL Credentials for gmail as relay host.Create a file named /etc/postfix/sasl_passwd and add below line. The username and password values must be replaced with valid gmail account.# vi /etc/postfix/sasl_passwd# [smtp.gmail.com]:587 username:passwordSave & Exit.Generate Postfix lookup table from sasl_passwd file by running below command.# postmap /etc/postfix/sasl_passwdMake sure the Gmail credential file is accessible only by root.# chown root:postfix /etc/postfix/sasl_passwd # chmod 640 /etc/postfix/sasl_passwdEnable Postfix on startup# systemctl enable postfixFinally, start the Postfix service.# systemctl start postfix Enable "Less Secure App "Default setting of Gmail allows only the most secure sign-ins, e.g logging in to Gmail through web browser. To permit relay requests log in to your Gmail accoun