在 bash 中更改变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10402537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change variables in bash
提问by pkruk
How do I change this var ?
如何更改此 var ?
max=0;
min=20000000;
cat |while read
do
read a
if [[ $a -gt $max ]]
then
max=a`
fi
`if [[ $a -lt $min ]]
then
min=a
fi
done
echo $max
echo $min
My min and max are still the same, 0 and 2000000. Can anybody help me with this ? I have no idea.
我的最小值和最大值仍然相同,0 和 2000000。有人可以帮助我吗?我不知道。
回答by Mat
The (main) problem with your script is that setting min
and max
happens in a subshell, not your main shell. So the changes aren't visible after the pipeline is done.
您的脚本的(主要)问题是设置min
和max
发生在子 shell 中,而不是您的主 shell。因此,管道完成后更改不可见。
Another one is that you're calling read twice - this might be intended if you want to skip every other line, but that's a bit unusual.
另一个是您调用 read 两次 - 如果您想跳过每隔一行,这可能是有意的,但这有点不寻常。
The last one is that min=a
sets min
to a
, literally. You want to set it to $a
.
最后一个是min=a
设置min
为a
,字面意思。您想将其设置为$a
.
Using process substitutionto get rid of the first problem, removing the (possibly) un-necessary second read, and fixing the assignments, your code should look like:
使用进程替换来解决第一个问题,删除(可能)不必要的第二次读取,并修复分配,您的代码应如下所示:
max=0
min=20000000
while read a
do
if [[ $a -gt $max ]]
then
max=$a
fi
if [[ $a -lt $min ]]
then
min=$a
fi
done < <(cat) # careful with the syntax
echo $max
echo $min