Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"set -e" in shell and command substitution

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?

like image 961
Ivan Tarasov Avatar asked Dec 30 '10 02:12

Ivan Tarasov


People also ask

What is set E in shell script?

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.

What is '- E used for in Linux?

-e: It is used to exit immediately if a command exits with a non-zero status.

What does e do in command line?

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.

What is E in bash command?

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.


1 Answers

Yes, inline the process substitution in the if-statement

#!/bin/bash

set -e

if ! output=$(possibly-failing-command); then
  ...
else
  ...
fi

Command Fails

$ ( 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

Command Works

$ ( 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
like image 137
SiegeX Avatar answered Oct 01 '22 02:10

SiegeX