views:

96

answers:

3

I have this script that I am currently running that works great for all instances but one:

 #!/bin/sh
 pdfopt test.pdf test.opt.pdf &>/dev/null
 pdf2swf test.opt.pdf test.swf
 [ "$?" -ne 0 ] && exit 2

More lines to execute follow the above code ...

How would I go about changing this script to run "pdf2swf test.pdf test.swf" if "pdf2swf test.opt.pdf test.swf" fails? If the second attempt fails, then I would "exit 2".

Thanks

+1  A: 

Maybe you want a Makefile instead of a shell script. A makefile aborts automatically it one of the commands fail. Alternatively, you can add [ "$?" -ne 0 ] && exit 2 after every command

Sjoerd
That won't work without explicit dependencies for both targets, and is questionable with `make -jxx` if they lack. Even if done correctly, its still a shell script, just wrapped up in a Makefile :)
Tim Post
Isn't the OP asking for do this OR do this to consider it a success? So this doesn't help. Also, if you want your shell script to exit if any of the commands returns non-zero use "#!/bin/sh -e" instead of using a makefile or writing 'exit 2' after every line.
Stephen
+5  A: 

Short circuiting "OR" should do what you want:

pdf2swf test.opt.pdf test.swf || pdf2swf test.pdf test.swf
Stephen
`pdf2swf test.opt.pdf test.swf || pdf2swf test.pdf test.swf || exit 2`
Dennis Williamson
+1  A: 

Try:

/path/to/pdfopt test.pdf test.opt.pdf >/dev/null && {

    pdf2swf test.opt.pdf test.swf
    ... maybe do more stuff here, in the future ...
    exit_here_nicely
} 

code_that_is_reached_if_pdfopt_failed

In your example:

pdfopt test.pdf test.opt.pdf &>/dev/null

... pdfopt runs in the background, you have no idea how long it may take to complete. Let it block, so the code in the parens is reached only if it worked.

A function wrapping that could easily launch in the background, but each process blocks until the first command exits as expected.

Tim Post
That gives an error. Omit the square brackets.
Dennis Williamson
@Dennis - it was psuedo code, but edited.
Tim Post