2.1.函数的定义和使用
函数基本使用
[root@VM_0_9_centos ~]# test()> {}-bash: syntax error near unexpected token `{}'[root@VM_0_9_centos ~]# test() {}-bash: syntax error near unexpected token `{}'[root@VM_0_9_centos ~]# test() > {> echo "test function"> }[root@VM_0_9_centos ~]# testtest function[root@VM_0_9_centos ~]# function greeting> {> echo "hello world"> }[root@VM_0_9_centos ~]# greeting hello world[root@VM_0_9_centos ~]#
实例一:写一个守护进程,nginx如果关闭自动开启
vim nginx_daemon.sh
#!/bin/bash##运行脚本的进程id,如果脚本名字有nginx字样,也需要把这个过滤掉this_pid=$$while truedops -ef |grep nginx |grep -v grep | grep -v $this_pid &> /dev/nullif [ $? -eq 0 ];then echo "Nginx is running well!" sleep 3else systemctl start nginx echo "Nginx is down,start it....."fidone
把这个脚本放到后台运行
nohup sh nginx_daemon.sh &
关闭后查看
tail -f nohup.out
2.2.向函数传递参数
shell中传参
function name{ echo "hello $1" echo "hello $2"}
函数调用
name derek alice
举例
[root@VM_0_9_centos shell_learn]# function greeting> {> echo "Hello $1"> }[root@VM_0_9_centos shell_learn]# [root@VM_0_9_centos shell_learn]# greeting derekHello derek[root@VM_0_9_centos shell_learn]# greeting aliceHello alice[root@VM_0_9_centos shell_learn]#
2.3.函数的返回值
返回值的方式
方式一:return方法二:echo
使用return返回值
- 使用return返回值,只能返回1-255的整数
- 函数使用return返回值,通常只是用来供其他地方调用 获取状态,因此通常仅返回0或1;0表示成功,1表示失败
使用echo返回值
- 使用echo可以返回任何字符串结果
- 通常用于返回数据,比如一个字符串值或者列表值
实例一
#!/bin/bash#this_pid=$$function is_nginx_running{ ps -ef |grep nginx |grep -v grep | grep -v $this_pid &> /dev/null if [ $? -eq 0 ];then return else return 1 fi}is_nginx_running && echo "nginx is runnig...." || echo "nginx is stop!"
实例二:获取用户列表
#!/bin/bash#function get_users{ users=`cat /etc/passwd | cut -d: -f1` echo $users}user_list=`get_users`index=1for user in $user_listdo echo "The $index user is: $user" index=$(($index+1))done
2.4.局部变量和全局变量
全局变量
- 不做特殊声明,shell中变量都是全局变量
- 大型脚本程序函数中慎用全局变量
局部变量
- 定义变量时,用local关键字
- 函数内和函数外存在相同的变量,函数内部覆盖函数外部变量
2.5.函数库
函数库
- 经常使用的重复代码封装成函数文件
- 一般不直接执行,而是由其它脚本调用
- 库文件名的后缀是任意的,但一般使用.lib
- 库文件通常没有可执行选项
- 库文件无需和脚本在同级目录,只需在脚本中引用时指定