Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change variables in bash

Tags:

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 2000000. Can anybody help me with this ? I have no idea.

like image 435
pkruk Avatar asked May 01 '12 18:05

pkruk


People also ask

How do I change variables in Bash?

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.

How do I use a variable in Bash?

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.

Can you have variables in Bash?

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.


Video Answer


1 Answers

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

like image 197
Mat Avatar answered Oct 18 '22 05:10

Mat