Search code examples
bashshellbin

Shell script to output the largest


How to write a script which will receive a list of parameters and output the number that is the largest. If no parameters are supplied, output an error message.

I wrote the following code to check if no parameters are supplied, output an error message.

#!/bin/bash
if [ "$#" -eq  "0" ]
then
  echo "No arugments supplied"
else
  echo "$# Parameter"

But I dont know how to continue...


Solution

  • Use sort -n (numeric) and -r (reverse) and then just pick the first line of the output -- like

    #!/bin/bash
    if [ "$#" -eq  "0" ]
    then
      echo "No arugments supplied"
    else
      echo "$# Parameter"
      for i in $*; do echo ${i}; done | sort -nr | head -1
    fi  
    

    Now the only problem you are facing is when the the input (the arguments) are not numbers -- but you didn't say anything about what should happen then.