Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

How to avoid syntax error on missing command line arguments?

Example shell script:

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

Output :

shell>sh shelltest 2 3
2
3
5

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
add comment

2 Answers

up vote 2 down vote accepted

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

For Example:

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

if [ "$#" -lt "4" ] 
then 
    echo -e $USAGE;    
else 
    var1=$2;
    var2=$4;
    echo `expr $var1 + $var2`;
fi
share|improve this answer
add comment

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

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

Which then does this:

% ./test.sh
./test.sh: 2: ./test.sh: 1: [Please specify the first number to add.]
% ./test.sh 1
./test.sh: 3: ./test.sh: 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
add comment

Your Answer

 
discard

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.