The the simpler form of a function is:
name () { commands return }I find no difference in a function with and without return.
Suppose the minimal code:
step_forward (){ echo "step one;" return
}
turn_around() { echo "turn around." return
}
step_forward
turn_aroundRun and check the exit status:
$ bash testing.sh
step one;
turn around.
$ echo $?
0Run it again after commenting out return
$ bash testing.sh
step one;
turn around.
$ echo $?
0In what circumstances should a function end with a return?
21 Answer
A return value is not required in a function. Normally a return would be used in a script for an exit value to be returned. Exit values are normally like a 1 or a 0 where a lot of scripters might use it for a 0 as successful and a 1 as not successful.
#!/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..."
fiExamples:
~$ ./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...And this answer I wrote a little bit ago does not have return values but still gives output
#!/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"Example:
terrance@terrance-ubuntu:~$ ./circ.bsh
Enter a radius: 6
Area of a circle is 113.04Hope this helps!