Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How to avoid syntax error on missing command line arguments?

Example shell script:

 echo $var1
 echo $var2
 var3=`expr $var1 + $var2`;
 echo $var3

Output :

shell>sh shelltest 2 3

Output :

    shell>sh shelltest
expr: syntax error

As no arguments are passed, How can I avoid this and pass my own message instead of "expr: syntax error"?

share|improve this question
up vote 2 down vote accepted

You can check missing argument in shell script using $# variable.

For Example:

#The following line will print no of argument provided to script
#echo $#
USAGE="$0 --arg1<arg1> --arg2<arg2>"

if [ "$#" -lt "4" ] 
    echo -e $USAGE;    
    echo `expr $var1 + $var2`;
share|improve this answer

I usually use the "Indicate Error if Null or Unset" parameter expansion to ensure that parameters are specified. For example:

var1="${1:?[Please specify the first number to add.]}"
var2="${2:?[Please specify the second number to add.]}"

Which then does this:

% ./
./ 2: ./ 1: [Please specify the first number to add.]
% ./ 1
./ 3: ./ 2: [Please specify the second number to add.]

From the manpage:

 ${parameter:?[word]}  Indicate Error if Null or Unset.  If parameter is
                       unset or null, the expansion of word (or a message
                       indicating it is unset if word is omitted) is
                       written to standard error and the shell exits with
                       a nonzero exit status.  Otherwise, the value of
                       parameter is substituted.  An interactive shell
                       need not exit.
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.