南通网站定制企业,php自己做网站访问量计算,广州网站定做教程,网站建设公司yu在命令行中使用函数 在命令行中创建函数 两种方法 单行方式来定义函数#xff1a;
$ function divem { echo $[ $1 / $2 ]; }
$ divem 100 5
20
$ 当你在命令行中定义函数时#xff0c;必须在每个命令后面加个分号#xff0c;这样 shell 就能知道哪里是命令的起止了
$ 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
value110
value25
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
$