更改bash中的变量 [英] Change variables in bash

查看:61
本文介绍了更改bash中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更改此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

我的最小值和最大值仍然相同,分别为0和2000000.有人可以帮助我吗?我不知道.

My min and max are still the same, 0 and 2000000. Can anybody help me with this ? I have no idea.

推荐答案

脚本的(主要)问题是设置minmax发生在子外壳中,而不是主外壳中.因此,更改完成后就看不到更改.

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.

另一种情况是您要调用两次读取-如果您想跳过每隔一行,可能会这样做,但这有点不寻常.

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.

最后一个是min=a从字面上将min设置为a.您要将其设置为$a.

The last one is that min=a sets min to a, literally. You want to set it to $a.

使用流程替换摆脱第一个问题,然后删除(可能)不必要的第二读,并修正了分配,您的代码应如下所示:

Using process substitution to 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

这篇关于更改bash中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆