Python Bash中的全局变量未更改

Python Bash中的全局变量未更改,python,bash,Python,Bash,下面的代码有问题。未更改runFail,因此无法在最后访问它,从而导致错误 runFail=1 pylint_run(){ if [ ! -f "$root/$1/$2/__init__.py" ]; then cd "$root/$1/$2" || exit pylintOutput=$(find . -iname "*.py" -print0 | xargs -0 pylint) else pylintOutput=$(pylint "$root/$1/$2") fi

下面的代码有问题。未更改runFail,因此无法在最后访问它,从而导致错误

runFail=1
pylint_run(){
if [ ! -f "$root/$1/$2/__init__.py" ]; then
    cd "$root/$1/$2" || exit
    pylintOutput=$(find . -iname "*.py" -print0 | xargs -0 pylint)
else
    pylintOutput=$(pylint "$root/$1/$2")
fi

echo "${pylintOutput}"
# This then scans for the line in the output containing the score
scoreLine=$(grep rated <<< "$pylintOutput")
IFS=" " read -r -a array <<< "$scoreLine"
# The score is the 6th column in that line
scoreVal=${array[6]}
# Snips the "out of ten" of the end
scoreVal=${scoreVal///10/}
# Sees if the pylint actually ran successfully and produced a score
if [ -z "$scoreVal" ]; then
    echo "Pylint failed to run"
    runFail=0
fi
# Checks if the score is good enough
# If not, it will say the score is too low and indicate a fail.
if (( $(echo "$scoreVal < 8" | bc -l) )); then
    echo "Score is less than 8 for '$2': FAIL"
    runFail=0
fi
echo "=================END OF TEST================"
}
# pylint_run [path/containing/scriptFolder] [scriptFolder]
# The tee command is then used to produce a report to be used as an 
artifact
pylint_run "gocd-helper-scripts/gocdhelp/" "gocdhelp" | tee gocdhelp-
report.txt
pylint_run "metrics-gocd/" "metrics" | tee metrics-report.txt
echo $runFail
if [[ $runFail = 1 ]]; then
    echo "Score is more than 8 for each tool: PASS"
    exit 0
else
    exit 1
fi
这里echo应该打印0,它当前打印1,因此应该退出1

如果您需要更多详细信息,请告诉我,我很困惑,并询问了同事我的代码出了什么问题,我不知道,因为我在bashshell中尝试了相同的方法,效果很好

实际上,我所做的只是设置一个变量,生成一个函数来更改该变量,调用该函数并测试变量是否已更改。很明显,它涉及到更改变量的代码,但无法全局更改变量,即使它应该可以

与此类似:

从函数运行中删除T形管可以解决问题,但我不明白为什么管道会以这种方式影响作用域

Bash版本是3.2.57,我正在终端中运行。/pylint checker.sh

| tee filename.txt
我需要使用

> >(tee filename.txt)

您正在管道中调用函数:

pylint_run "gocd-helper-scripts/gocdhelp/" "gocdhelp" | tee gocdhelp-report.txt
这意味着双方都在一个地下室中运行。子shell无法更改父环境的值,因此以这种方式调用的pylint_run无法更改全局变量

您可以使用重定向来实现相同的效果,而不需要pylint_运行进程的子shell,如

pylint_run "gocd-helper-scripts/gocdhelp/" "gocdhelp" > >(tee gocdhelp-report.txt)

它在进程替换shell中运行tee,并让pylint_在父进程的shell中运行,以便可以修改这些变量。

您使用的是哪个版本的BASH?对不起,我帮不了你。但我知道下一个人会问这个问题,如果他知道你的BASH版本,他可能知道答案。很显然,了解脚本的运行方式可能会很有趣,所以请也包括在内。@0xbaadf00d对不起,我已经更新了我的post.NP,我只是在新用户给我发帖子时做这件事,我被指示帮助他们正确地发帖子。需要一个完整的示例,这几乎是标准做法。重复问题所需的每一条信息都很简短。谢谢,我理解子shell,但我肯定需要更多地了解重定向以及什么语法/方法导致子shell。
pylint_run "gocd-helper-scripts/gocdhelp/" "gocdhelp" > >(tee gocdhelp-report.txt)