1

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 
1

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.

  • May this be elaborated more? Say, how to add exit in if branch in above example? What should be inside if condition? – Rohail Abbas Aug 6 '16 at 1:51
1

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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