Comment puis-je utiliser la valeur entière renvoyée par une fonction dans un script shell qui prend certains arguments en input?
J'utilise le code suivant:
fun() { echo "hello ${1}" return 1 } a= fun 2 echo $a
Je ne sais pas comment j'appelle cette fonction. J'ai essayé les methods ci-dessous, aucun bot ne semble fonctionner:
a= fun 2 a=`fun 2` a=${fun 2}
Le code de sortie est contenu dans $?
:
fun 2 a=$?
vous pouvez jeter un oeil à la question suivante: https://stackoverflow.com/questions/8742783/returning-value-from-fall-function-in-shell-script avec une réponse longue et bien expliquée. Cordialement.
#!/bin/bash function producer_func() { echo "1" echo "[ $1 ]" echo "2" echo "3" } function returner_func() { echo "output from returner_func" return 1 } #just print to stdout from function producer_func "aa ww" echo "--------------------" #accumulate function output into variable some_var=$(producer_func "bbb ccc") echo -e "<$some_var>" echo "--------------------" #get returned value from function, may be integer only returner_func echo "returner_func returned $?" echo "--------------------" #accumulate output and get return value some_other_var=`returner_func` echo "<$some_other_var>" echo "returner_func returned $?" echo "--------------------"
tutoriel bash sympa, lien points vers l'invocation des fonctions