From: Chris F.A. Johnson on
On 2010-07-26, Jack Bates wrote:
> How can I make my script exit immediately if "svn export" in the
> following exits with a non-zero status?
>
> #!/bin/sh
>
> # Exit immediately if a simple command exits with a non-zero status
> set -e
>
> [...]
>
> # Export from vendor repository
> REV=`svn export http://svn.symfony-project.com/branches/1.4 $TMPDIR/
> symfony | sed -n '$s/^Exported revision \([[:digit:]]\+\)\.$/\1/p'`
>
> [...]
>
> Here's the complete (short) script, http://qubit-toolkit.googlecode.com/svn/symfony/cron.daily/drop
>
> We use it nightly to pull upstream code into our repository. It should
> exit immediately if a command exits with a non-zero status - however
> last night "svn export" failed, the script didn't exit, and
> consequently the upstream code was removed from our repository
>
> When the script calls "svn export", it needs,
>
> 1) to get the "exported revision" from standard output
> 2) to exit immediately if the exit code is non-zero
>
> The script exits immediately if most commands exit with a non-zero
> status, because it calls "set -e"
>
> I guess that "set -e" doesn't apply in the case of "svn export"
> because it's executed in a subshell?
>
> How can I get the "exported revision" from standard output, and exit
> immediately if the exit code is non-zero?

Test the command itself:

REV=`svn export http://svn.symfony-project.com/branches/1.4 $TMPDIR/symfony |
sed -n '$s/^Exported revision \([[:digit:]]\+\)\.$/\1/p'` || exit 1


--
Chris F.A. Johnson, author <http://shell.cfajohnson.com/>
===================================================================
Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
Pro Bash Programming: Scripting the GNU/Linux Shell (2009, Apress)

From: pk on
On Tue, 27 Jul 2010 11:51:08 -0700 (PDT)
Jack Bates <jack.bates(a)gmail.com> wrote:

> > REV=`svn
> > exporthttp://svn.symfony-project.com/branches/1.4$TMPDIR/symfony | sed
> > -n '$s/^Exported revision \([[:digit:]]\+\)\.$/\1/p'` || exit 1
>
> Thank you very much Chris, but this isn't working - the script still
> doesn't exit immediately
>
> Here's a simplified example,
>
>
> #!/bin/sh
>
> set -e
>
> FOO=`false | sed s/foo/bar/g` || exit 1
>
> echo didnt exit
>
>
> ^ This example should exit immediately after the call to "false" - it
> shouldn't execute the last line, "echo didn't exit"

With bash, you can use the PIPESTATUS array to check the exit status of
commands other than the last in apipeline.

Alternatively, you have to run the commands by themselves, eg

svn export http://blah > /tmp/tempfile
sed whatever /tmp/tempfile
....

With set -e, a failing command will terminate the script (or use command ||
exit 1)