Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit code of command substitution in bash local variable assignment [duplicate]

How can I check the exit code of a command substitution in bash if the assignment is to a local variable in a function?
Please see the following examples. The second one is where I want to check the exit code.
Does someone have a good work-around or correct solution for this?

$ function testing { test="$(return 1)"; echo $?; }; testing 1 $ function testing { local test="$(return 1)"; echo $?; }; testing 0 
like image 875
Vampire Avatar asked Mar 01 '12 21:03

Vampire


People also ask

How do I find exit code in bash?

Checking Bash Exit Code Launch a terminal, and run any command. Check the value of the shell variable “$?” for the exit code. $ echo $? As the “date” command ran successfully, the exit code is 0.

What is exit 2 in shell script?

Exit code 2 signifies invalid usage of some shell built-in command. Examples of built-in commands include alias, echo, and printf.

What does bash do when it performs command substitution?

3.5. 4 Command Substitution Bash performs the expansion by executing command in a subshell environment and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting.


1 Answers

If you look at the man file for local (which is actually just the BASH builtins man page), it is treated as its own command, which gives an exit code of 0 upon successfully creating the local variable. So local is overwriting the last-executed error code.

Try this:

function testing { local test; test="$(return 1)"; echo $?; }; testing 

EDIT: I went ahead and tried it for you, and it works.

like image 63
Chriszuma Avatar answered Oct 09 '22 14:10

Chriszuma