Skip to content
Advertisement

Print error for missing argument

I am trying to write a script which will check number of arguments for first and second number; if both variable entered, it will do the calculation; if one argument is missing, it will print error message. Here what I’ve done so far:

#!/bin/bash
echo -n "Enter the first number: "
read num1
echo -n "Enter the second number: "
read num2

if [ $# -le 1 ]; then
    echo "Illegal number of arguments"
    exit
else
    echo "The sum is: " $(( num1 + num2 ))
fi

I am always getting error message even though I enter both of the numbers. What am I missing? Please help.

Advertisement

Answer

Test Your Assigned Variables, Not Positional Parameters

Your variables num1 and num2 aren’t positional parameters, and so the special parameter $# is probably not what you think it is. You should change your conditional to check that both variables are set. For example:

declare -i num1 num2

read -p 'Enter the first number: '  num1
read -p 'Enter the second number: ' num2

if [ -z "$num1" ] || [ -z "$num2" ]; then
    echo "Illegal number of arguments" >&2
else
    echo "The sum is: $((num1 + num2))"
fi
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement