Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "local" sweep the return code of a command?

Tags:

bash

shell

local

This Bash snippet works as expected:

$ fun1() { x=$(false); echo "exit code: $?"; } $ fun1 exit code: 1 

But this one, using local, does not as I would have expected:

$ fun2() { local x=$(false); echo "exit code: $?"; } $ fun2 exit code: 0 

Can anyone explain why does local sweep the return code of the command?

like image 615
tokland Avatar asked Dec 12 '10 10:12

tokland


People also ask

Which command shows the return code of the last executed command?

Extracting the elusive exit code To display the exit code for the last command you ran on the command line, use the following command: $ echo $?

Which command is used to return an exit code?

How to get the exit code of a command. To get the exit code of a command type echo $? at the command prompt. In the following example a file is printed to the terminal using the cat command.

What is an exit code or return code in Linux?

Overview. In Linux, when a process is terminated, it returns an exit code. Upon successful execution, this code is equal to zero. Any non-zero exit code indicates that some error occurred.

What is exit code of command false '?

false returns an exit status value of 1 (failure). It ignores any arguments given on the command line. This option can be useful in shell scripts.


1 Answers

The reason the code with local returns 0 is because $? "Expands to the exit status of the most recently executed foreground pipeline." Thus $? is returning the success of local

You can fix this behavior by separating the declaration of x from the initialization of x like so:

$ fun() { local x; x=$(false); echo "exit code: $?"; }; fun exit code: 1 
like image 190
SiegeX Avatar answered Sep 19 '22 09:09

SiegeX