2

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"?

Ahn
  • 181
  • 3
  • 5
  • 13

2 Answers2

4

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
Abhijeet Kasurde
  • 983
  • 9
  • 20
4

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.
mgorven
  • 30,615
  • 7
  • 79
  • 122