LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   if...elif...else BASH ladder problems (https://www.linuxquestions.org/questions/linux-newbie-8/if-elif-else-bash-ladder-problems-844739/)

bdrockwell 11-16-2010 10:50 PM

if...elif...else BASH ladder problems
 
Our assignment is to take in two numbers and add them. While the inputs will always be numbers, we are to inform the user if they are doing it wrong.

My code:

Quote:

#!/bin/sh

if [[ -n "$3" ]]
then
echo too many inputs
elif [[ -z "$1"]]
then
echo you need to have two inputs
elif [[ -z "$2" ]]
then
echo you need to have two inputs
else
echo $1 + $2 = `expr $1 + $2`
fi
My error:

Quote:

[brockwel@darrow1-p hw5]$ problem1.sh
problem1.sh: line 6: syntax error in conditional expression
problem1.sh: line 7: syntax error near `then'
problem1.sh: line 7: `then'
The code worked fine before I tried to idiot-proof it. I'll probably end up nesting the if statements checking if the first two inputs are not null, but I'm more annoyed at why the script isn't working.

Help would be very appreciated.

archieval 11-16-2010 11:06 PM

For every conditions, do it with one pair of open/close brackets only. and put space after '[', and before ']'

bdrockwell 11-16-2010 11:34 PM

Thanks for the help

grail 11-16-2010 11:38 PM

I would suggest looking at the variable $# as it can potentially change 3 ifs into one. (see here)

I would then suggest looking at the (()) construct found here as a much cleaner way of doing the arithmetic

Lastly, if you use code tags instead of quote tags then your formatting will remain :)


All times are GMT -5. The time now is 12:41 PM.