简体   繁体   English

如何避免 E042 本地声明隐藏使用 bashate 的错误?

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

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.当你使用 local 时,Bashate linter 会抛出一个错误,但它没有给出如何重写代码以使其通过 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来自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")"
    ...
}

Apparently, all it takes to placate bashate in this case is separation of the variable declaration from the subshell capture:显然,在这种情况下安抚bashate需要的只是将变量声明与子外壳捕获分离:

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

This way you can check for errors that might have occured in the subshell:通过这种方式,您可以检查子 shell 中可能发生的错误:

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

Initially I thought bashate may have complained because the status var $?最初我认为bashate可能会抱怨,因为状态 var $? was not handled, or that there might exist a method of capturing subshell output that I was not aware of.没有被处理,或者可能存在一种我不知道的捕获 subshel​​l 输出的方法。 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.有关类似形式,请参阅@grawity 的此答案

$? reports the status of the local command rather than the subshell's exit status if used in a composite expression:如果在复合表达式中使用,则报告local命令的状态而不是子 shell 的退出状态:

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.有关更多信息,请参阅@ryenus 的这个答案

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.最后,线程中的这个答案详细说明了可移植性和风格bashate规定的一些缺陷,这强化了这样一种观念,即风格指南只是工具,可能是也可能不是适合工作的工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM