博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
2.shell编程-函数的高级用法
阅读量:4512 次
发布时间:2019-06-08

本文共 2104 字,大约阅读时间需要 7 分钟。

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
  • 库文件通常没有可执行选项
  • 库文件无需和脚本在同级目录,只需在脚本中引用时指定

 

转载于:https://www.cnblogs.com/derek1184405959/p/11099961.html

你可能感兴趣的文章
Android自带样式
查看>>
iSCSI 原理和基础使用
查看>>
Gym101350 J Lazy Physics Cat
查看>>
Java读取文件方法大全
查看>>
解决mysql无法显示中文/MySQL中文乱码问号等问题
查看>>
CentOS 7.2 配置mysql5.7
查看>>
第一次写博客用来记录自己的工程师生涯。
查看>>
python输出转义字符
查看>>
java基础43 IO流技术(输入字节流/缓冲输入字节流)
查看>>
ASP.NET那点不为人知的事(四)
查看>>
☆ [HNOI2012] 永无乡 「平衡树启发式合并」
查看>>
git 常用命令
查看>>
Springboot 使用 JSR 303 对 Controller 控制层校验及 Service 服务层 AOP 校验,使用消息资源文件对消息国际化...
查看>>
ES6--4.解构赋值
查看>>
CCF系列之图像旋转(201503-1)
查看>>
edit.h 再转换到 VS2010 的问题
查看>>
POJ 3134 Power Calculus ★(记录状态的BFS)
查看>>
POJ 3678 Katu Puzzle(POJ 六道2-SAT之一)
查看>>
面向对象初识
查看>>
LeetCode: Find All Duplicates in an Array
查看>>