函数的更简单形式是:
name () { commands return }
我发现有和没有 return 的函数没什么区别。
假设最小代码:
step_forward (){
echo "step one;"
return
}
turn_around() {
echo "turn around."
return
}
step_forward
turn_around
运行并检查退出状态:
$ bash testing.sh
step one;
turn around.
$ echo $?
0
注释掉之后再次运行return
$ bash testing.sh
step one;
turn around.
$ echo $?
0
在什么情况下函数应该以返回结束?
答案1
return
函数中不需要值。通常在return
脚本中会使用 来返回退出值。退出值通常类似于1
或 ,0
许多脚本编写者可能会将其用作 表示0
成功和1
表示不成功。
#!/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
例子:
~$ ./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...
我之前写的这个答案没有返回值,但仍然给出输出 https://askubuntu.com/a/1023493/231142
#!/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"
例子:
terrance@terrance-ubuntu:~$ ./circ.bsh
Enter a radius: 6
Area of a circle is 113.04
希望这可以帮助!