2.shell编程-函数的高级用法
发布时间:2020-12-15 21:12:12 所属栏目:安全 来源:网络整理
导读:2.1.函数的定义和使用 函数基本使用 [[email?protected]_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 ~] # te
2.1.函数的定义和使用函数基本使用 [[email?protected]_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 ~]# test test 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 true do ps -ef |grep nginx |grep -v grep | grep -v $this_pid &> /dev/null if [ $? -eq 0 ];then echo "Nginx is running well!" sleep 3 else systemctl start nginx echo "Nginx is down,start it....." fi done 把这个脚本放到后台运行 nohup sh nginx_daemon.sh & 关闭后查看 tail -f nohup.out
2.2.向函数传递参数shell中传参 function name { echo "hello $1" echo "hello $2" } 函数调用 name derek alice 举例 [[email?protected]_0_9_centos shell_learn]# function greeting > { > echo "Hello $1" > } [root@VM_0_9_centos shell_learn]# [[email?protected]_0_9_centos shell_learn]# greeting derek Hello derek [root@VM_0_9_centos shell_learn]# greeting alice Hello alice [root@VM_0_9_centos shell_learn]# 2.3.函数的返回值返回值的方式 方式一:return 方法二:echo 使用return返回值
使用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=1 for user in $user_list do echo "The $index user is: $user" index=$(($index+1)) done 2.4.局部变量和全局变量全局变量
局部变量
2.5.函数库函数库
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- webservice 测试窗体只能用于来自本地计算机的请求
- Scala / Lift:CSS Selector Transforms和DispatchSnippet
- twitter-bootstrap – Bootstrap折叠导航菜单
- AngularJs+JQuery:模糊查询过滤内容,下拉菜单排序,过滤敏
- 离子网内的角 – 离子 – 复选框使网格空白
- webservice学习笔记——入门篇
- scala – 如何在不升级到Akka HTTP的情况下停止使用路由DSL
- scala – 如何在Mesos集群上使用Spark时预先打包外部库
- 尝试读取整个文件时出现MalformedInputException
- docker – CoreDNS无法在Kubernetes集群中运行