Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use local in Bash in conjunction with set -o errexit?

I'm new to Bash and I had a hard time to figure out why when I was using set -o errexit and a command fail, the script was not exiting.

It seems because I declared a local variable!

Please tell me how I can use local variable and set -o errexit at the same time.

Example:

#!/bin/bash
set -o errexit
set -o nounset
set -o pipefail

function test {
 local output=$(ls --badoption)
 echo "error code is $?"
 echo "output=$output"
}

test

Result:

./test.sh
ls: illegal option -- -
usage: ls [-ABCFGHLOPRSTUWabcdefghiklmnopqrstuwx1] [file ...]
error code is 0
output=

But:

#!/bin/bash
set -o errexit
set -o nounset
set -o pipefail

function test {
 output=$(ls --badoption)
 echo "error code is $?"
 echo "output=$output"
}

test

Result:

ls: illegal option -- -
usage: ls [-ABCFGHLOPRSTUWabcdefghiklmnopqrstuwx1] [file ...]
like image 822
Sebastien Tardif Avatar asked Nov 22 '25 12:11

Sebastien Tardif


1 Answers

It's because set -o errexit (or running bash with -e) only affects simple commands (as defined in the bash man page). cmd in local output=$(cmd) isn't considered a simple command, so -e doesn't have any affect (and $? doesn't have any relation to how cmd exited). A simple workaround is to split the line by replacing:

local output=$(ls --badoption)

with:

local output

output=$(ls --badoption)

In my testing that does everything you want, it will exit immediately, and if you replace the ls --badoption with just ls, it works, and setting output before calling test then echoing it afterwords shows output really is local to test.

like image 145
blm Avatar answered Nov 24 '25 04:11

blm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!