76 votes

Quelle est la bonne façon de tester une valeur de retour de fonction bash ?

Je voudrais tester une valeur de retour de fonction bash dans une instruction if comme celle-ci :

 if [[ func arg ]] ; then …

mais je reçois des messages d'erreur comme : conditional binary operator expected.

Quel est le bon moyen de le faire?

Est-ce :

  if [[ $(func arg) ]] ; then ...

20voto

Pedro Inácio Points 41

Cela m'a été utile, j'ajouterais donc les détails suivants.

Si vous devez tester deux conditions, l'une étant l'état de sortie de la fonction/commande et l'autre, par exemple la valeur de la variable, utilisez ceci :

 if func arg && [[ $foo -eq 1 ]]; then echo TRUE; else echo FALSE; fi

19voto

Alex Gitelman Points 15062

Cette erreur semble se produire si la fonction renvoie plus d'un mot.

Par exemple, 1 2 .

Citez-le simplement :

 "$(func arg)"

Échantillon:

 $ if [[ 1 2 ]] ; then echo 1 ; fi
-bash: conditional binary operator expected
-bash: syntax error near `2'
$ if [[ "1 2" ]] ; then echo 1 ; fi
1

Et si vous comparez 0 vs non 0, utilisez simplement

 if [[ "$(func arg)" != "0" ]]

3voto

codeforester Points 17582

Sur une note connexe, si la fonction renvoie une variété de codes de sortie au lieu de vrai/faux, alors :

 func args; ec=$?      # call function and grab the exit code
                      # it is better to have them on the same line so that a future addition of a command
                      # before the case statement wouldn't break the logic
case $ec in
  value1) # commands
          ;;
  value2) # commands
          ;;
  *)      # commands
          ;;
esac

1voto

Rinzler Points 29

Réalisant qu'il s'agit d'un vieux post... Voici mon conseil à ce sujet :

select fournit beaucoup d'aide ici.

 PS3="What's your choice? (^D to stop choosing): "
select mainmenuinput in updatesystem installsamba installvsftpd installwebmin configuresambaforactivedirectory quitprogram; do
    case "$mainmenuinput" in

    "updatesystem")
        echo "Update System..."
    ;;

    "installsamba")
        echo "Installing Samba..."
    ;;

    #echo And so forth...
    esac
done

echo Done

Pour obtenir de l'aide sur select , consultez man bash et recherchez 'select'. Ne fournir aucune entrée répétera le menu.

 select name [ in word ] ; do list ; done
       The  list  of words following in is expanded, generating a list of items.  The set of expanded words is printed on the standard error, each preceded by a number.  If the in word is omitted, the
       positional parameters are printed (see PARAMETERS below).  The PS3 prompt is then displayed and a line read from the standard input.  If the line consists of a number corresponding  to  one  of
       the  displayed  words, then the value of name is set to that word.  If the line is empty, the words and prompt are displayed again.  If EOF is read, the command completes.  Any other value read
       causes name to be set to null.  The line read is saved in the variable REPLY.  The list is executed after each selection until a break command is executed.  The exit status  of  select  is  the
       exit status of the last command executed in list, or zero if no commands were executed.

Exemple de sortie :

 [rinzler ~] $ ./test.sh 
1) updatesystem                      4) installwebmin
2) installsamba                      5) configuresambaforactivedirectory
3) installvsftpd                     6) quitprogram
What's your choice? (^D to stop choosing): 1
Update System...
What's your choice? (^D to stop choosing): 2
Installing Samba...
What's your choice? (^D to stop choosing): 
1) updatesystem                      4) installwebmin
2) installsamba                      5) configuresambaforactivedirectory
3) installvsftpd                     6) quitprogram
What's your choice? (^D to stop choosing): 
Done

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X