JP Vossen on 18 Aug 2008 20:35:16 -0700


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

[PLUG] if command then foo else bar


At the PLUG West meeting, Toby asked about using a bash 'if' without a 
'test', but testing the command instead.  Like:
	if command; then
		foo
	elif
		bar
	fi

This one bites me every once in a while too, since that's how it 
"logically" should work.  The answer is to forget about the "if" part 
and use && or ||.  You can't do an else, since the || and && operators 
work on the immediately preceding command.  But you don't need an else, 
since you can write it like this:

	command || {
		<stuff to do if it failed>
		exit 1
	}
	<"else" script continues>

Or, very oddly:
	command && {
		<stuff to do if it WORKED>
		exit 1  # ???
	}
	<script continues ???>


Note that the { } "block" requires surrounding white space and either a 
newline or ; before the closing }.

	Good:
		cmd || { echo failed; exit 1; }
	Bad:
		cmd || { echo failed; exit 1}


Also note that these constructs only work if <command> sets correct exit 
status (that is, 0 on success, >0 on failure; the opposite of Perl).


Finally, note that a "set -e" option near the top of your script might 
be in order.  That causes the script to exit if *any* command fails. 
You will see this in lots of system scripts, e.g., /etc/init.d/*.  That 
can save an awful lot of 'command || exit 1' typing.

	$ help set
	set: set [--abefhkmnptuvxBCHP] [-o option] [arg ...]
	        -e  Exit immediately if a command exits with a
		    non-zero status.


Later,
JP
----------------------------|:::======|-------------------------------
JP Vossen, CISSP            |:::======|        jp{at}jpsdomain{dot}org
My Account, My Opinions     |=========|      http://www.jpsdomain.org/
----------------------------|=========|-------------------------------
"Microsoft Tax" = the additional hardware & yearly fees for the add-on
software required to protect Windows from its own poorly designed and
implemented self, while the overhead incidentally flattens Moore's Law.
___________________________________________________________________________
Philadelphia Linux Users Group         --        http://www.phillylinux.org
Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce
General Discussion  --   http://lists.phillylinux.org/mailman/listinfo/plug