Comment éviter une erreur de syntaxe en l'absence d'arguments de la ligne de commande?

Comment éviter une erreur de syntaxe en l'absence d'arguments de la ligne de commande?

Exemple de script shell:

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

Production :

shell>sh shelltest 2 3
2
3
5

Production :

    shell>sh shelltest
expr: syntax error

Étant donné que les arguments ne sont pas transmis, car je peux éviter cela et transférer mon propre message à la place. «expr: syntax error»?
Invité:

Hannah

Confirmation de:

J'utilise habituellement la divulgation de paramètres "point une erreur si Null ou Unset», Pour s'assurer que les paramètres sont spécifiés. Par exemple:

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

Qu'est-ce que ça fait alors:

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

De
http://manpages.ubuntu.com/man ... ttoc2
:

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

Alice

Confirmation de:

Vous pouvez vérifier l'argument manquant dans le script shell en utilisant

$#

variable.

Par exemple:

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

</arg2></arg1>

Pour répondre aux questions, connectez-vous ou registre