O 'retorno' dentro da função é um requisito obrigatório?

3

A forma mais simples de uma função é:

name () { commands return }

não vejo diferença em uma função com e sem retorno.
Suponha o código mínimo:

step_forward (){
    echo "step one;"
    return
}
turn_around() {
    echo "turn around."
    return
}

step_forward
turn_around

Executar e verificar o status de saída:

$ bash testing.sh
step one;
turn around.
$ echo $?
0

Execute-o novamente depois de comentar return

$ bash testing.sh
step one;
turn around.
$ echo $?
0

Em que circunstâncias uma função deve terminar com um retorno?

    
por JawSaw 14.04.2018 / 06:58

1 resposta

4

Um valor return não é necessário em uma função. Normalmente, um return seria usado em um script para um valor de saída a ser retornado. Os valores de saída normalmente são como 1 ou 0 , em que muitos scripts podem usá-lo para um 0 como bem-sucedido e um 1 como não bem-sucedido.

#!/bin/bash
#The following function returns a value of 0 or 1
function if_running(){
    ps -ef | grep -w "$1" | grep -v grep > /dev/null
    if [[ $? == 0 ]]; then
        return 0
    else
        return 1
    fi
}

#Read in name of a running process
read -p "Enter a name of a process: "

#Send REPLY to function
if_running $REPLY

#Check return value and echo appropriately
if [[ $? == 0 ]]; then
   echo "Return value is $?"
   echo "$REPLY is running..."
else
   echo "Return value is $?"
   echo "$REPLY is not running..."
fi

Exemplos:

~$ ./ps_test.bsh 
Enter a name of a process: ls
Return value is 1
ls is not running...

~$ ./ps_test.bsh 
Enter a name of a process: bash
Return value is 0
bash is running...

E essa resposta que escrevi há pouco não tem valores de retorno, mas ainda fornece um link de saída

#!/bin/bash
function area(){
    circ=$(echo "3.14 * $1^2" | bc)
}

#Read in radius
read -p "Enter a radius: "

#Send REPLY to function
area $REPLY

#Print output
echo "Area of a circle is $circ"

Exemplo:

terrance@terrance-ubuntu:~$ ./circ.bsh 
Enter a radius: 6
Area of a circle is 113.04

Espero que isso ajude!

    
por Terrance 14.04.2018 / 07:28