函数:
- 代码块
- 代码块中包含一段可以被调用执行
- 通过函数可以减少重复性的工作
定义函数的方式
方法1
funName() {
函数体
}
方法2
function funName(){
函数体
}
函数的执行结果
- 函数的输出函数中的echo输出的信息,就是函数的输出
- 函数的返回状态函数中的return的值,就是函数的返回值状态
向函数传递数据
- 通过为止变量来传递
- $1、$2、$3
- $@
- $#
案例
#!/bin/bash
# 定义一个函数
show(){
echo "123"
echo "456"
}
# 定义函数
get(){
read -p "enter a name: " name
echo $name
}
# 调用函数
show
# 调用函数
get
注意:
- 函数必须先定义,后使用,否则程序报错
函数分离
- 函数文件:这个文件中仅仅是定义多个函数
- 主程序:在主程序调用函数文件中的函数调用函数的方法. /path/to/filesource /path/to/file
案例2
#定义函数 /root/fun
fun1(){
echo "hi boys"
}
fun2(){
echo "hello boys"
}
# 主程序文件
#!/bin/bash
if [ -f /root/fun ];then
. /root/fun
fi
fun1
fun2
fun2
fun1
函数中可以调用函数
#!/bin/bash
fun1(){
echo "123"
}
fun2(){
echo "start"
fun1
echo "end"
}
fun2
案例:
#!/bin/bash
getinfo(){
grep "^$1\>" /etc/passwd | awk -F ":" '{print $1,$3}'
}
main(){
while true
do
read -p "enter a user name or quit: " userName
if [ "$userName" == "quit" ];then
echo "bye"
break
fi
if id $userName &>/dev/null;then
getinfo $userName
break
else
echo "no such user."
fi
done
}
main
变量的作用域
- 在主程序中定义的变量,在函数中可以使用
- 在函数中可以修改主程序中的变量
- 如果禁止在函数中修改主程序的变量,可以将变量定义为局部变量
- 定义局部变量的方法:local 变量=值
#!/bin/bash
num1=1
echo "主程序,调用函数前num1=$num1"
fun1(){
local num1=2
echo "函数中,num1=$num1"
local num2=5
}
fun1
echo "主程序,调用函数后num1=$num1"
echo "$num2"
练习:写一个脚本,完成如下功能 1、显示如下菜单 disk) show disk info mem) show memory info cpu) show cpuinfo 2、显示用户选定的内容
#!/bin/bash
showMenu(){
echo "
cpu - show cpu information
mem - show memory information
disk - show disk information
"
}
worker(){
while true
do
showMenu
read -p "Enter a choice: " cho
case $cho in
"cpu")
cat /proc/cpuinfo | awk -F ":" '/name/{print $2}';;
"mem")
free -m | awk 'NR==2{print $0}' ;;
"disk")
df -h -P | awk 'NR==2{print $0}';;
*)
echo "error";;
esac
done
}
worker