标签:需要 shel 程序 全局 外部变量 shell编程 token etc else
函数基本使用
[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
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]#
返回值的方式
方式一: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
全局变量
局部变量
函数库
标签:需要 shel 程序 全局 外部变量 shell编程 token etc else
原文地址:https://www.cnblogs.com/derek1184405959/p/11099961.html