ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

2.shell编程-函数的高级用法

2019-06-28 09:41:00  阅读:160  来源: 互联网

标签:shell centos 编程 VM echo nginx 用法 root


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 ~]# 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

举例

[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 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返回值

  • 使用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=1

for user in $user_list
do
    echo "The $index user is: $user"
    index=$(($index+1))
done

2.4.局部变量和全局变量

全局变量

  • 不做特殊声明,shell中变量都是全局变量
  • 大型脚本程序函数中慎用全局变量

局部变量

  • 定义变量时,用local关键字
  • 函数内和函数外存在相同的变量,函数内部覆盖函数外部变量

2.5.函数库

函数库

  • 经常使用的重复代码封装成函数文件
  • 一般不直接执行,而是由其它脚本调用
  • 库文件名的后缀是任意的,但一般使用.lib
  • 库文件通常没有可执行选项
  • 库文件无需和脚本在同级目录,只需在脚本中引用时指定

 

标签:shell,centos,编程,VM,echo,nginx,用法,root
来源: https://www.cnblogs.com/derek1184405959/p/11099961.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有