函数
概念
函数是一段完成特定功能的代码片段(块)
在shell中定义了函数,就可以使代码模块化,便于复用代码
注意函数必须先定义才可以使用。
重点
传参 $1,$2
局部变量 local
返回值 return 即 $?
定义函数
方法一:
函数名() {
函数要实现的功能代码
}
方法二:
function 函数名 {
函数要实现的功能代码
}
调用函数
语法
函数名
函数名 参数1 参数2
====================================================================
示例1:初识函数
需求
编写循环脚本,功能菜单
provide these tools:
show disk info(d)
show mem info(m)
show cpu info©
quit(q)
思路
1,编写菜单和判断
2,添加循环
3,添加函数
示例
#!/bin/bash
show_menu() {
cat << EOF
provide these tools:
show disk info(d)
show mem info(m)
show cpu info(c)
quit(q)
EOF
}
while :
do
show_menu
read -p "Input choice: " choice
case $choice in
d)
echo "===========disk info=============="
df -hT
;;
m)
echo "==========meme info==============="
free -m
;;
c)