Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating number of arguments

Tags:

bash

I apologize for the beginners question ahead of time but I cannot get this chunk of code to work properly. I was asked to make a basic program which asks the user for 3 numbers and then checks which is the highest value and prints the results, as well as makes sure there are three numbers put in. It can determine which is his highest and im getting it to output results properly but I cant seem to figure out how to get it to validate that there are three numbers put in.

I have done research and even pulled some code from the teachers example about how to check the number of arguments but I still cant get it to work.

#!/bin/bash

echo "Please enter three numbers:"
read a b c
if [ $# -ne 3 ]
    then
    echo "You need three numbers"
    exit -1
fi
if [ $a -gt $b -a $a -gt $c ]
      then
              LARGEST=$a
elif [ $b -gt $a -a $b -gt $c ]
      then
              LARGEST=$b
elif [ $c -gt $a -a $c -gt $b ]
      then
              LARGEST=$c
elif [ $a -eq $b -a $a -eq $c -a $b -eq $c -eq $b ]
then
LARGEST="All three values are equal."
fi
echo "The largest values is $LARGEST"

When I enter three numbers (7 8 9) I expect to get back: "The largest value is 9"

however I get this instead:

./values.sh: line 6 [0: command not found
The largest value is 9

Am i missing something blatantly obvious here? I know i need an operator to make my original if statement work but am i using the wrong one?

like image 213
Preston Dotsey Avatar asked Oct 16 '22 15:10

Preston Dotsey


1 Answers

The [ -z "$c" ] test solves it for the code you posted. Working code:

#!/bin/bash

echo "Please enter three numbers:"
read a b c d
if [ -z "$c" ]
    then
    echo "You need three numbers"
    exit -1
fi
if [ -n "$d" ]
then
   echo "enter only three numbers"
   exit -1
fi
if [ $a -gt $b -a $a -gt $c ]
      then
              LARGEST=$a
elif [ $b -gt $a -a $b -gt $c ]
      then
              LARGEST=$b
elif [ $c -gt $a -a $c -gt $b ]
      then
              LARGEST=$c
elif [ $a -eq $b -a $a -eq $c -a $b -eq $c -eq $b ]
then
LARGEST="All three values are equal."
fi
echo "The largest values is $LARGEST"

Output:

$ ./t.sh
Please enter three numbers:
7 8
You need three numbers
$ ./t.sh
Please enter three numbers:
7 8 9
The largest values is 9
like image 130
L. Scott Johnson Avatar answered Nov 15 '22 09:11

L. Scott Johnson