Change variables in bash

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)