如何避免缺less命令行参数的语法错误?

如何避免缺less命令行参数的语法错误?

示例shell脚本:

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

输出:

 shell>sh shelltest 2 3 2 3 5 

输出:

  shell>sh shelltest expr: syntax error 

由于没有parameter passing,我怎样才能避免这一点,并通过我自己的消息,而不是“expr:语法错误”?

您可以使用$#variables检查shell脚本中缺less的参数。

例如:

 #!/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 

我通常使用“指示错误如果空或未设置”参数扩展,以确保参数指定。 例如:

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

那么这是什么:

 % ./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.] 

从手册:

  ${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.