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.
The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.
You don't have to use any special character before the variable name at the time of setting value in BASH like other programming languages. But you have to use '$' symbol before the variable name when you want to read data from the variable.
You can use variables as in any programming languages. There are no data types. A variable in bash can contain a number, a character, a string of characters. You have no need to declare a variable, just assigning a value to its reference will create it.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With