0

I want to write a bash script with -e option so it stops on any error, but want to allow a specific line to return an error code different to zero and use it in the logic:

#/bin/bash -e
do_something_and_return_errcode
if [ $? -eq 2 ]; then
    specific_stuff
fi

The script would normally end in do_something_and_return_errcode. I could avoid by doing

do_something_and_return_errcode || true

but this would make $? return 0 and I cannot use $PIPESTATUS because this is not a pipeline.

Ramillete
  • 89
  • 5

3 Answers3

2

First, using set -e is highly error-prone, and not universally agreed on as good practice.

That said, consider:

err=0
do_something_and_return_errcode || err=$?

Another option is simply to temporarily disable the flag:

set +e ## disable the effect of bash -e / set -e
do_something_and_return_errcode; err=$?
set -e ## ...and reenable that flag after
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
0

Use the solution suggested by Charles Duffy:

https://stackoverflow.com/a/36727957/887539

Leaving this post for reference:

You could pipe it though, consider the following example:

% cat pipetst.sh
#!/bin/bash
set -e
false | true
printf "Pipe: %d, exit: %d\n" "${PIPESTATUS[0]}" "$?"
% ./pipetst.sh
Pipe: 1, exit: 0

This is a hack and shouldn't be used in production code, I would much rater remove the set -e and implement error handling where ever needed.

If you need the output to go to stdout you can just pipe to cat:

(echo hello; exit 1) | cat
Community
  • 1
  • 1
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
0

You can use PIPESTATUS to see return status from all of the pipeline commands. See the Bash man page sections on "Pipelines" and the "PIPESTATUS" Shell Variable. If the last command is always successful, then the script will not exit because of set -e.

> cat /tmp/emptyfile | grep "sometext" | echo "OK"; echo ${PIPESTATUS[@]}
OK
cat: /tmp/emptyfile: No such file or directory
1 1 0
> touch /tmp/emptyfile
> cat /tmp/emptyfile | grep "sometext" | echo "OK"; echo ${PIPESTATUS[@]}
OK
0 1 0
> echo "Find sometext here" > /tmp/emptyfile
> cat /tmp/emptyfile | grep "sometext" | echo "OK"; echo ${PIPESTATUS[@]}
OK
0 141 0
Eric Bolinger
  • 2,722
  • 1
  • 13
  • 22