How to print error and exit if command fails?


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting How to print error and exit if command fails?
# 1  
Old 04-23-2009
How to print error and exit if command fails?

Guys any tips on printing a certain error message to stderr and exiting should a command fail within a ksh script? I'm trying to null some output files.

Touch isn't suitable as i need to null them.
print "" > file isn't suitable as i need to check elsehere for if they are 0bytes or not.

I've tried these below examples and none work correctly. I don't want to have to put a check after each command as :-

Code:
if [[ $? -ne 0 ]];then
   print "error blah blah" >&2
   exit 2
fi

Below tests don't work correctly. I'm guessing its spawning something.

Code:
OUTFILE=/tmp/out

# Null outfiles. Security already checked

> ${OUTFILE} || print "ERROR: blah blah \n" >&2 ; exit 2   #doesnt work

> ${OUTFILE} || (print "ERROR: blah blah \n" >&2 ; exit 2 )  #doesn't work

> ${OUTFILE} || (print "ERROR: blah blah \n" >&2 && exit 2) #doesnt work

if [[ -n "$(> ${OUTFILE} 2>&1)" ]];then
     print "ERROR: blah blah \n" >&2
     exit 2
fi    # doesnt work

Any ideas or alternatives?
# 2  
Old 04-23-2009
Specifically about reporting and exiting, this is a slightly more condensed idiom:

Code:
test $condition || { print "Crap blew up; exiting"; exit 2; }

You could also directly test for the result of your command:

Code:
command || { print "Crap blew up; exiting"; exit 2; }

I enjoy reading that out loud to myself as "either you do this or DIE!", as if threathening the script.

Last edited by EagleFlyFree; 04-23-2009 at 03:17 PM..
# 3  
Old 04-23-2009
Thanks dude thats worked like a charm.

Seems i was almost there but didn't use the correct { }

Could you explain the difference between { } and ( ) in the command grouping? Also i notied the ; at the end before } is vitally important otherwise the next command doesn't work.

e.g

Code:
This works and exits if cant null but echos got to here if can.

> ${OUTFILE} || { print "ERROR: cannot null output file. Exiting\n" >&2; exit 2; }
> ${TMPFILE} || { print "ERROR: cannot null tmp file. Exiting\n" >&2; exit 2; }

echo "got to here"

This doesnt work and never gets to echo even if null is successful

> ${OUTFILE} || { print "ERROR: cannot null output file. Exiting\n" >&2; exit 2 }
> ${TMPFILE} || { print "ERROR: cannot null tmp file. Exiting\n" >&2; exit 2 }

echo "got to here"

# 4  
Old 04-23-2009
() executes the statements in a new subshell, with separate state. {} executes stuff in the current shell.

Example:

Code:
(aVariable="hello"); echo $aVariable

this doesn't print "hello" because the variable was assigned inside a new shell, whose state was discarded when the () expression ended. Think of variable scoping in C; variables live and die inside the block where they're declared.

Code:
{aVariable="hello"; }; echo $aVariable

this prints "hello" because the variable was assigned in the same shell as the next statement.

It's the same difference as:
Code:
sh myScript.sh

and
Code:
source myScript.sh



Also, yes, you need a semicolon to end the last statement inside {}; that's how the shell's grammar is defined.
Kind of how you can either do this:
Code:
if $condition; then $statements; fi

or this, using newlines instead of semicolons to separate the syntax parts:
Code:
if $condition
then
    $statements
fi

According to the bash man page, it's different from () because { and } are reserved words instead of metacharacters, which means they don't automatically cause word breaks. Presumably the same applies in the rest of the shells.

Last edited by EagleFlyFree; 04-23-2009 at 03:14 PM..
# 5  
Old 04-24-2009
Dude thats real great and an informative reply. Thanks a lot. Its certainly giving me a better understanding of the shell rather than just trying things until they work Smilie
# 6  
Old 04-24-2009
Don't mention it; I love yapping about bash.
Its man page is long and daunting, but flick through it every once in a while; you're bound to learn great tidbits every time.
The parts about history and readline are particularly cool, and they're handy and fun to use.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

Linux shell | how to exit a script if any command fails.

Hi, i am new here let me say HI for all. now i have a question please: i am sending one command to my machine to create 3 names. if one of the names exists then the box return error message that already have the name but will continue to create the rests. How i can break the command and... (7 Replies)
Discussion started by: Amiri
7 Replies

2. Shell Programming and Scripting

How to exit from shell script if above condition fails?

HI cd ${back_home} if above back_home does not exist, then script shoul exit. Please let us know how to do that (7 Replies)
Discussion started by: buzzme
7 Replies

3. Shell Programming and Scripting

Script to check one command and if it fails moves to other command

Input is list of Server's, script is basically to remove old_rootvg, So it should check first command "alt_rootvg_op -X old_rootvg" if it passes move to next server and starts check and if it fails moves to other command "exportvg old_rootvg" for only that particular server. I came up with below,... (6 Replies)
Discussion started by: aix_admin_007
6 Replies

4. Shell Programming and Scripting

SH script, variable built command fails, but works at command line

I am working with a sh script on a solaris 9 zone (sol 10 host) that grabs information to build the configuration command line. the variables Build64, SSLopt, CONFIGopt, and CC are populated in the script. the script includes CC=`which gcc` CONFIGopt=' --prefix=/ --exec-prefix=/usr... (8 Replies)
Discussion started by: oly_r
8 Replies

5. UNIX for Advanced & Expert Users

Equivalents of tee command to find exit status of command

Hi, Want to log the output of command & check the exit status to find whether it succeeded or failed. > ls abc ls: abc: No such file or directory > echo $? 1 > ls abc 2>&1 | tee log ls: abc: No such file or directory > echo $? 0 Tee commands changes my exit status to be always... (7 Replies)
Discussion started by: vibhor_agarwali
7 Replies

6. Shell Programming and Scripting

Need help! command working ok when executed in command line, but fails when run inside a script!

Hi everyone, when executing this command in unix: echo "WM7 Fatal Alerts:", $(cat query1.txt) > a.csvIt works fine, but running this command in a shell script gives an error saying that there's a syntax error. here is content of my script: tdbsrvr$ vi hc.sh "hc.sh" 22 lines, 509... (4 Replies)
Discussion started by: 4dirk1
4 Replies

7. Shell Programming and Scripting

Linux:Program exit with displaying a print feature

hi All I have a scritp running which connects to a local host and then gets a value from a field and then ftp that value to antoher server. It is running fine, and from crontab it gives the output to a file, the problem is sometime it doesnt run but if i check the output file it does not show one... (0 Replies)
Discussion started by: imran721
0 Replies

8. Shell Programming and Scripting

How to print exit status in AWK

Hi all, How can I print the exit status in AWK? echo $? doesnt work for me Thanks (4 Replies)
Discussion started by: Pauline mugisha
4 Replies

9. Shell Programming and Scripting

How to capture actual error message when a command fails to execute

I want to capture actual error message in case the commands I use in my shell script fails. For eg: ls -l abc.txt 2>>errorlog.txt In this case I understand the error message is written to the errorlog.txt and I assume its bacause the return code from the command ls -l abc might return 2 if... (3 Replies)
Discussion started by: prathima
3 Replies

10. Shell Programming and Scripting

Print Error with set command

I need to print some mandatory instructions if something fails in the script. I am using set -e to check and exit the script if some scripts/commands return non zero exit code. Is there any way to print these instructions with set command?? (0 Replies)
Discussion started by: Shribigb
0 Replies
Login or Register to Ask a Question