is_nginx_running && echo"Ningx is running" || ehco "Ningx is Stop"# Ningx is running
获取系统所有的用户
#!/bin/bash## get all usernamefunction get_users
{
users=`cat /etc/passwd | cut -d : -f1`
echo$users
}
# echo all users name
users=`get_users`
index=1
for s in$usersdoecho"The $index user is $s."
index=$(($index+1))
done
变量的作用域
在shell中如果不做特殊声明,那么变量不管是在函数体内还是函数外都是全局变量
如果要在函数内使用局部变量需要使用local关键字
谨慎使用全局变量。
函数没有运行 函数体定义的全局变量函数外部或者其他函数内部访问无效。
案列
#!/bin/bash#
var1="hello world"functiontest1
{
var2=123
}
functiontest2
{
local var3="local variable"echo$var2
}
functiontest3
{
echo$var3
}
# 测试echo$var1$var2$var3# hello world test1
test2
test3
echo$var1$var2$var3# hello world 123
函数库
我们可以通过定义一些通用的函数或者复用度比较高的函数来形成我们的函数库
案例 : 定义加减乘除 和 显示系统信息的库
# add reduce multiple divide sys_loadfunction add
{
echo"`expr $1 + $2`"
}
function reduce
{
echo"$(($1 - $2))"
}
function multiple
{
echo"`expr $1 \* $2`"
}
function divide
{
echo"$(($1 / $2))"
}
function sys_load
{
echo"Memory Info : "echo
free -m
echoecho"Disk Usage"echo
df -h
echo
}