Reputation: 145
I am having an issue counting the arguments I enter in my shell script. My script is suppose to echo "You have entered too many arguments" by using and Else statement at the end of my code. If I enter more than 3 I get nothing. Am I missing something simple or should I change this to a case statement. I am new to shell scripting so any help would be greatly appreciated.
#!/bin/bash
clear
Today=$(date +"%m-%d-%y")
echo -en '\n'
echo "To find out more about this calculator please refer to the calc.readme file."
echo -en '\n'
echo "You entered $*"
echo -en '\n'
if [ "$#" -eq "3" ]; then
if [ "$2" == "+" ]; then
answer=`expr $1 + $3`
echo "You entered the correct amount of arguments"
echo -en '\n'
echo "Your total is: "`expr $1 + $3`
echo "[$Today]: $@ = $answer" >> calc.history
elif [ "$2" == "-" ]; then
answer=`expr $1 - $3`
echo "You entered the correct amount of arguments"
echo -en '\n'
echo "Your total is: "`expr $1 - $3`
echo "[$Today]: $@ = $answer" >> calc.history
elif [ "$2" == "*" ]; then
answer=`expr $1 \* $3`
echo "You entered the correct amount of arguments"
echo -en '\n'
echo "Your total is: "`expr $1 \* $3`
echo "[$Today]: $@ = $answer" >> calc.history
elif [ "$2" == "/" ]; then
asnwer=`expr $1 / $3`
echo "You entered the correct amount of arguments"
echo -en '\n'
echo "Your total is: "`expr $1 / $3`
echo "[$Today]: $@ = $answer" >> calc.history
else
echo -en '\n'
echo "You entered too many arguments."
fi
fi
Upvotes: 1
Views: 82
Reputation: 531165
Your else
statement is associated with the wrong if
statement, but you can replace the big if-elif
chain with a single case
statement.
#!/bin/bash
clear
today=$(date +"%m-%d-%y")
echo
echo "To find out more about this calculator please refer to the calc.readme file."
echo
echo "You entered $*"
echo
if [ "$#" -eq "3" ]; then
echo "You entered the correct amount of arguments"
case $2 in
[+-*/])
echo
answer=$(( $1 $2 $3 ))
echo "Your total is $answer"
echo "[$today]: $@ = $answer" >> calc.history
;;
*) echo "Unrecognized operator $2"
;;
esac
else
echo
echo "You entered too many arguments."
fi
Upvotes: 3
Reputation: 29050
Your if statements are wrongly nested. You wrote:
if <test on number of arguments>
if <values>
else
<wrong number of arguments>
fi
fi
while you should have written:
if <test on number of arguments>
if <values>
fi
else
<wrong number of arguments>
fi
Upvotes: 3