"set -e" in shell and command replacement

In shell scripts, set -e often used to make them more reliable by stopping the script when some of the commands executed from the script exit with a non-zero exit code.

It is usually easy to indicate that you do not need some of the following commands by adding || true || true to the end.

The problem arises when you really care about the return value, but don't want the script to stop at a non-zero return code, for example:

 output=$(possibly-failing-command) if [ 0 == $? -a -n "$output" ]; then ... else ... fi 

Here we want to check the exit code (thus, we cannot use || true inside the command substitution expression) and get the output. However, if a command in command substitution does not work, the entire script stops due to set -e .

Is there a clean way to prevent the script from stopping here without dropping -e and after that setting it back?

+4
source share
1 answer

Yes, enter process substitution in if-statement

 #!/bin/bash set -e if ! output=$(possibly-failing-command); then ... else ... fi 

Team Failure

 $ ( set -e; if ! output=$(ls -l blah); then echo "command failed"; else echo "output is -->$output<--"; fi ) /bin/ls: cannot access blah: No such file or directory command failed 

Team work

 $ ( set -e; if ! output=$(ls -l core); then echo "command failed"; else echo "output is: $output"; fi ) output is: -rw------- 1 siegex users 139264 2010-12-01 02:02 core 
+3
source

Source: https://habr.com/ru/post/1333753/


All Articles