36

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 ]]
    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.

3
  • 3
    also max=a should be max=$a, same with min=a should be min=$a Commented May 1, 2012 at 18:49
  • What should be min if every values are greater than 20000000 ? I guess that min and max should be your first value... Commented May 1, 2012 at 20:25
  • Possible duplicate of A variable modified inside a while loop is not remembered Commented Jan 18, 2018 at 2:33

1 Answer 1

48

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

Sign up to request clarification or add additional context in comments.

2 Comments

4th problem: unmotivated backticks in the middle of the script, not explainable by beginner mistake. :)
In Bash (and Ksh and Zsh), I recommend this form: if (( a > max )). Also, if cat is not a placeholder for something else, then the whole redirection and process substitution can be eliminated since the script will read from stdin by default anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.