1

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
1
  • You need to review what type LIST is? You set it as an empty array and then assign a scalar value using read. You need to include the -a switch to read to maintain LIST as an array Commented Jun 14, 2017 at 4:53

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

1 Comment

I like this solution. I had originally added an OR to my MIN logic (..|| MIN -eq "") and it worked out. What I had failed to remember, being use to other programming languages, is that these were string literals and not integers. It made sense as to why ${LIST[0]} was printing out the whole set up numbers (or single string). Thanks, @agc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.