Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I have a shell script that calls on a Perl script to do some file processing. The Perl scripts exits with either a zero or one value. I have the Unix set -e command at the beginning of my script to abort the script if the Perl script exits with a value of one. I was just wondering if there is any command in Unix that I can use that would execute one command before the script is aborted if the Perl script exits with a one value? Essentially, I want the script to send me an email stating whether the Perl script ran successfully. My code looks like this right now:

#!/bin/bash

set -e

function email_success {
#Some code for the email 
}

function email_fail {
#Some code for the email
}

usr/bin/perl perlscript.pl

if [$? -eq 0]; then 
 email_success
else 
 email_fail
fi 

#More commands to be executed if its successful 
share|improve this question

2 Answers 2

up vote 1 down vote accepted

Just don't use set -e and add an exit to your if fail branch. If you want that behavior for the rest of the script add the set -e after the email call.

share|improve this answer
    
Awesome, that worked great. Thank you! –  Cpoole Jul 16 at 15:04

Use set -e

You can write:

#!/bin/bash
set -e

# function email_success {...}

# function email_fail { ... }

if /usr/bin/perl perlscript.pl; then
  email_success
else
  email_fail
  exit 1
fi

#More commands to be executed if its successful 

Explanation:

Bash Reference Manual says:

-e Exit immediately if a pipeline, which may consist of a single simple command, returns a non-zero status. The shell does not exit if the command that fails is part of the test in an if statement.

Conditional Constructs (if):

The syntax of the if command is

if test-commands; then
  consequent-commands;
[elif more-test-commands; then
  more-consequents;]
[else alternate-consequents;]
  fi

The test-commands list is executed, and if its return status is zero, the consequent-commands list is executed. If ‘else alternate-consequents’ is present, and the final command in the final if or elif clause has a non-zero exit status, then alternate-consequents is executed.

See also: Use the Unofficial Bash Strict Mode (Unless You Looove Debugging)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.