function
function_name param1 param2 …
function_name () {startment1...}function function_name () {...}# sayHello 如果将执行放在前面会报错function sayHello(){echo "hello world"echo `date`}sayHello# B函数调用A函数function john() {echo "hello, this is John"}function alice() {johnecho "Hello, this is Alice"}alice
function sum () {let "z = $1 + $2"return $z # return 的值必须在0~255范围内}sum 22 4echo $? #输出26sum 250 16echo $? # 输出10
length() {str=$1result=0if [ "$str" != "" ];thenresult=${#str}fiecho "$result"}len=$(length "abc123")echo $len #输出6
函数别名
alias name=”command”
alias ls="ls -l" # 定义别名unalias ls #删除别名
1.命令行中输入 lsl() 定义一个函数
$ lsl()
> {
> ls -l “$@”
> }
2.命令行中输入 lsl
就会执行 ls -l “$@” 指令了
3.unset lsl 删除lsl函数
4.命令行中输入 lsl,此时提示
bash: lsl: command not found
移动参数的位置
func () {while (($# > 0))doecho $1shift # shift指令会改变$#的值,会将所有的参数都左移动一位done}func $@# ./xx.sh a b c# a# b# c
通过 getopts 接收函数参数
getopts optstring [args]
#! /bin/bashfunc() {echo $#while getopts ":a:b:c:" argdocase "$arg" ina)echo "-a ${OPTARG}";;b)echo "-b ${OPTARG}";;c)echo "-c ${OPTARG}";;*)echo "* ${OPTARG}";;esacdone}func $@#$ ./test.sh -a hello -b world -c aaa -l bbb#8#-a hello#-b world#-c aaa#* l
