在命令行中使用函數
在命令行中創建函數
兩種方法
單行方式來定義函數:
$ function divem { echo $[ $1 / $2 ]; }?
$ divem 100 5?
20?
$?
當你在命令行中定義函數時,必須在每個命令后面加個分號,這樣 shell 就能知道哪里是命令的起止了:
$ function doubleit { read -p "Enter value: " value; echo $[ $value * 2 ]; }?
$?
$ doubleit?
Enter value: 20?
40?
$?
多行方式來定義函數
$ function multem {?
> echo $[ $1 * $2 ]?
> }?
$ multem 2 5?
10?
$?
在.bashrc 文件中定義函數
直接定義函數
$ cat .bashrc?
# .bashrc?
# Source global definitions?
if [ -r /etc/bashrc ]; then?. /etc/bashrc?
fi?
function addem {?echo $[ $1 + $2 ]?
}?
$
?
該函數會在下次啟動新的 bash shell 時生效。隨后你就能在系統中的任意地方使用這個函數了。
源引函數文件
只要是在 shell 腳本中,就可以用 source 命令(或者其別名,即點號操作符)將庫文件中的函數添加到.bashrc 腳本中:
$ cat .bashrc?
# .bashrc?
# Source global definitions?
if [ -r /etc/bashrc ]; then?. /etc/bashrc?
fi?
. /home/rich/libraries/myfuncs?
$?
$ addem 10 5?
15?
$ multem 10 5?
50?
$ divem 10 5?
2?
$
shell會將定義好的函數傳給子 shell 進程,這些函數能夠自動用于該 shell 會話中的任何 shell 腳本。
$ cat test15?
#!/bin/bash?
# using a function defined in the .bashrc file?
value1=10?
value2=5?
result1=$(addem $value1 $value2)?
result2=$(multem $value1 $value2)?
result3=$(divem $value1 $value2)?
echo "The result of adding them is: $result1"?
echo "The result of multiplying them is: $result2"?
echo "The result of dividing them is: $result3"?
$?
$ ./test15?
The result of adding them is: 15
The result of multiplying them is: 50
The result of dividing them is: 2
$
?