shell脚本进阶函数实现
1.定义函数
语法一:
func_name(){
...函数体...
}
语法二:
function func.name{ ...函数体... }
语法三:
function func_name(){ ...函数体... }
例:定义一个简单的函数
[root@centos7 data]# func1(){ hostname; uanme -r; hostname -I; }
执行:
[root@centos7 data]# func1 centos7.localdomain 3.10.0-1160.el7.x86_64 192.168.93.145 192.168.122.1 fd15:4ba5:5a2b:1008:37a:d5f9:1a01:2c29
2.显示系统中目前支持的函数列表
[root@centos7 data]# declare -F

3.显示每个函数的定义
[root@centos7 data]# declare -f
4.在脚本中写入函数
例子:判断操作操作系统版本安装httpd/apache2
#!/bin/bash
OS_type(){
if grep -i -q ubuntu /etc/os-release;then
echo ubuntu
elif grep -i -q centos /etc/os-release;then
echo centos
else
echo "OS can not be supported!"
fi
}
if [ `OS_type` = centos ];then
yum -y install httpd
elif [ `OS_type` = ubuntu ];then
apt -y install apache2
else
echo "OS can not be supported!"
fi


5.1)写一个专门装函数的文件,方便以后引用
#!/bin/bash
OS_type(){
if grep -i -q ubuntu /etc/os-release;then
echo ubuntu
elif grep -i -q centos /etc/os-release;then
echo centos
else
echo "OS can not be supported!"
fi
}
color(){
RED="echo -e \E[1;31m"
GREEN="echo -e \E[1;32m"
END="\E[0m"
}

2)修改4的脚本
#!/bin/bash
.function
if [ `OS_type` = centos ];then
yum -y install httpd
elif [`OS_type` = ubuntu ];then
apt -y install apache2
else
echo "OS can not be supported!"
fi
color
${RED}"安装成功"$END

注意一点:若函数内有变量,不仅需要定义,还需要执行。
6.有参数的函数
例子:判断ip是否为合法ip
is_ipaddr(){
[[ "$1" =~ ^([0-9]{1,3}\.){3}\.[0-9]{1,3}$ ]] || { echo "$1" is not valid ip!"; return 1; }
}
记录于2022/3/5-18:17

浙公网安备 33010602011771号