In shell scripts set -e
is often used to make them more robust by stopping the script when some of the commands executed from the script exits with non-zero exit code.
It's usually easy to specify that you don't care about some of the commands succeeding by adding || true
at the end.
The problem appears when you actually care about the return value, but don't want the script to stop on non-zero return code, for example:
output=$(possibly-failing-command)
if [ 0 == $? -a -n "$output" ]; then
...
else
...
fi
Here we want to both check the exit code (thus we can't use || true
inside of command substitution expression) and get the output. However, if the command in command substitution fails, the whole script stops due to set -e
.
Is there a clean way to prevent the script from stopping here without unsetting -e
and setting it back afterwards?
Set -e commandIt terminates the execution when the error occurs. 'foo' is a non-existent command but bash still executed the third line after encountering the error at the second line. We can use the set command to stop termination.
-e: It is used to exit immediately if a command exits with a non-zero status.
You can disable command extensions for a particular process by using /e:off. You can enable or disable extensions for all cmd command-line options on a computer or user session by setting the following REG_DWORD values: HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\EnableExtensions\REG_DWORD.
by Aqsa Yasin. Set –e is used within the Bash to stop execution instantly as a query exits while having a non-zero status. This function is also used when you need to know the error location in the running code.
Yes, inline the process substitution in the if-statement
#!/bin/bash
set -e
if ! output=$(possibly-failing-command); then
...
else
...
fi
$ ( 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
$ ( 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With