Thankless Noodle
Thankless Noodle

Reputation: 13

Unix Scripting - Finding Minimum and Maximum (Bash Shell)

My code below is part of an assignment, but I'm racking my head against the desk not understanding why it won't assign a "MIN" value. I tried assigning the MIN and MAX to ${LIST[0]} just to have the first index in place, but it returns the whole array, which doesn't make sense to me. I'm executing this on a CentOS VM (which I can't see making a difference). I know the beginning of the first and second "if" statements need better logic, but I'm more concerned on the MIN and MAX outputs.

#!/bin/bash
LIST=()

read -p "Enter a set of numbers. " LIST

MIN=
MAX=

if [ ${#LIST[*]} == 0 ]; then echo "More numbers are needed."; fi

if [ ${#LIST[@]} -gt 0 ]; then
        for i in ${LIST[@]}; do
                if [[ $i -gt $MAX ]]; then
                        MAX=$i
                fi

                if [[ $i -lt $MIN ]]; then
                        MIN=$i
                fi
        done

echo Max is: $MAX.
echo Min is: $MIN.

fi

Upvotes: 1

Views: 4234

Answers (1)

agc
agc

Reputation: 8406

The code is almost functional.

  1. Since $LIST is an array, not a variable, change read -p "Enter a set of numbers. " LIST to:

    read -p "Enter a set of numbers. " -a LIST

  2. Move the $MIN and $MAX init code down 5 lines, (just before the for loop):

    MIN=
    MAX=
    

    ...and change it to:

    MIN=${LIST[0]}
    MAX=$MIN
    

And it'll work. Test:

echo 3 5 6 | ./minmax.sh 

Output:

Max is: 6.
Min is: 3.

Upvotes: 1

Related Questions