如何避免缺少命令行参数的语法错误?
示例 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
由于没有传递参数,我该如何避免这种情况并传递我自己的消息而不是“expr:语法错误”?
答案1
您可以使用$#
变量检查 shell 脚本中缺少的参数。
例如:
#!/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
答案2
我通常使用“如果为空或未设置则指示错误”参数扩展来确保指定了参数。例如:
#!/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.