Change variables in bash

前端 未结 1 1909
Happy的楠姐
Happy的楠姐 2021-02-18 23:07

How do I change this var ?

max=0;
min=20000000;
cat |while read
do
    read a
    if [[ $a -gt $max ]]
    then
        max=a`
    fi
    `if [[ $a -lt $min ]]
         


        
相关标签:
1条回答
  • 2021-02-18 23:55

    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.

    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
    

    0 讨论(0)
提交回复
热议问题