How to I avoid E042 local declaration hides errors with bashate?

222 Views Asked by At

Bashate linter throws an error when you use local but it gives no indicarion on how to rewrite the code to make it pass the linting.

Obviously that I could disable that check but that not the point, the idea is to find a way to write the code in a better way.

Example from https://github.com/openstack/kolla-ansible/blob/master/tools/kolla-ansible#L6

function find_base_dir {
    local real_path=$(python -c "import os;print(os.path.realpath('$0'))")
    local dir_name="$(dirname "$real_path")"
    ...
}
1

There are 1 best solutions below

0
On

Apparently, all it takes to placate bashate in this case is separation of the variable declaration from the subshell capture:

function func {
    local var
    var="$(...)"
    ...
}

This way you can check for errors that might have occured in the subshell:

var="$(...)"
status=$?

Initially I thought bashate may have complained because the status var $? was not handled, or that there might exist a method of capturing subshell output that I was not aware of. It was not, and I was not. Some related points however:

$? can be captured in an atomic expression:

output=$(inner) || exit $?

see this answer by @grawity for similar forms.

$? reports the status of the local command rather than the subshell's exit status if used in a composite expression:

f() { local    v=$(echo data; false); echo output:$v, status:$?; }
g() { local v; v=$(echo data; false); echo output:$v, status:$?; }
$ f     # fooled by 'local' with inline initialization
output:data, status:0
$ g     # a good one
output:data, status:1

see this answer by @ryenus for more information.

Finally, this answer among others in the thread detail some deficiencies in terms of portability and the style bashate prescribes, which reinforces the notion that style guides are just tools that may or may not be the right tool for the job.