Find highest number - working but need help!

Hello all, I am new to this and need some help or maybe steer me to the right direction!

I wrote a script to get the highest number and prints it on the screen, the script basically asks the user to input numbers, and then prints the highest number! very simple

it works like this

$sh max.sh
4 6 8 9
The highest number is: 9

my question is, instead of asking the users for numbers to input, how can i make the script to calculate inputted numbers right away when you execute the script, like this:

$sh max.sh 6 8 9
The highest number is: 9

please help :confused:

#!/bin/bash

read num
MAX="0"
for i in $num; do
   if [ $MAX -lt $i ] ; then
   MAX=$(echo $i)
   fi
done
echo "The highest number is: $MAX"

#END

max.sh:

#!/bin/bash

typeset -i MAX=0
for ((i=1;i<=$#;i++))
do
   eval a=\$$i
   if [ $a -gt $MAX ] ; then
      MAX=$a
   fi
done
echo "The highest number is: $MAX"

max.sh 8 3 9

Thans vgersh99 for the quick reply, unfortunately, i tried your code and get an error

max.sh: 3: typeset not found
max.sh: 4 Syntax error: Bad for loop variable

Since you have BASH, just

MAX=0

.

Also a=${!i}

Can you elaborate a little better!

Instead of typesetting MAX to 0, just do

MAX=0

Instead of using that eval thing, just do

a=${!i} since ${!VAR} returns the contents of the variable named in VAR, not the contents of VAR itself.

1 Like

I did it like this:

#!/usr/local/bin/bash

MAX=0
for ((i=1;i<=$#;i++))
do
   a=${!i}
   if [ $a -gt $MAX ] ; then
      MAX=$a
   fi
done
echo "The highest number is: $MAX"

Still throws this error:

Syntax error: Bad for loop variable

Try

MAX=0
for i in "$@"
do
        [ "$i" -gt "$MAX" ] && MAX=$i
done

Should work in nearly any shell.

1 Like

Worked like a charm :smiley: you are da man my friend!