Changing variables in bash

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 2,000,000. Can someone help me with this? I have no idea.

+8
bash
source share
1 answer

The main problem with your script is that setting min and max happens in a subshell, and not in your main shell. Thus, the changes are not visible after the completion of the pipeline.

Another is that you invoke reading twice - this may be intended if you want to skip any other line, but this is a bit unusual.

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

Using process substitution to get rid of the first problem, deleting the (possibly) unnecessary second read and committing the assignments, your code should look like this:

 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 

+13
source share

All Articles