![使用读取和函数计算面积](https://linux22.com/image/1155200/%E4%BD%BF%E7%94%A8%E8%AF%BB%E5%8F%96%E5%92%8C%E5%87%BD%E6%95%B0%E8%AE%A1%E7%AE%97%E9%9D%A2%E7%A7%AF.png)
我打算计算圆的面积。
#! /usr/local/bin/bash
read -p "Enter a radius: "
area () {
a=$(( 3 * $REPLY * 2 ))
return $a
}
echo $(area)
运行但不返回任何内容
$ bash area.sh
Enter a radius: 9
然后通过引用来重构它
#! /usr/local/bin/bash
read -p "Enter a radius: " radius
area (radius) {
a=$(( 3 * $radius * 2 ))
return "$a"
}
echo "$(area)"
它仍然不能正常工作。
bash area.sh
Enter a radius: 9
area.sh: line 3: syntax error near unexpected token `radius'
area.sh: line 3: `area (radius) {'
如何做这样的计算?
答案1
这是一个快速脚本,它接受半径的输入,然后将其提供给函数,area()
然后回显返回值。这适用于bc
已安装的二进制计算器。
#!/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
或者我稍微扩展了一下脚本,以显示更多从命令行或脚本本身读取变量的内容:
#!/bin/bash
function area(){
areacirc=$(printf "3.14 * $1^2\n" | bc)
diamcirc=$(printf "2 * $1\n" | bc)
circcirc=$(printf "2 * 3.14 * $1\n" | bc)
}
#Read in radius from command line or from read
if [[ $1 == "" ]]; then
read -p "Enter a radius: "
else
printf "Radius of a cirle is $1\n"
REPLY=$1
fi
#Send REPLY to area function
area $REPLY
#Print output from variables set by area function
printf "Diameter of a circle is $diamcirc\n"
printf "Circumference of a circle is $circcirc\n"
printf "Area of a circle is $areacirc\n"
例子:
terrance@terrance-ubuntu:~$ ./area.bsh 6
Radius of a cirle is 6
Diameter of a circle is 12
Circumference of a circle is 37.68
Area of a circle is 113.04
或者
terrance@terrance-ubuntu:~$ ./area.bsh
Enter a radius: 13
Diameter of a circle is 26
Circumference of a circle is 81.64
Area of a circle is 530.66
答案2
Bash 中的函数没有命名参数。您不能执行以下操作:
area (foo) { ...
function area (foo) { ...
你可以做:
area () {
local radius a # set a local variable that does not leak outside the function
radius=$1 # Save the first parameter to local variable
a=$(( 3 * radius * 2 ))
echo "$a"
}
进而:
echo "$(area "$REPLY")" # use $REPLY as the first argument
因为return
设置了函数的退出状态,而$(area)
使用函数的输出。它们是不同的。
另外,虽然 bash 不支持浮点运算,但它支持指数运算:
$ bash -c 'echo $((3 * 3 ** 2))'
27