当前位置 博文首页 > ai_benwoniu的博客:2019-03-06笔记—shell脚本编程一(基础理论
shell是一种脚本语言,是用户界面和系统底层之间的通信桥梁,是系统命令的集合,支持一些基本的编程元素,例如:
shell脚本可以实现自动化运维,能大成都的增加人工运维效率
以之前监控nginx状态的脚本为例
[root@linux2019_2 ~]# ] vi /usr/local/sbin/nginx_status.sh
#!/bin/bash
url="http://127.0.0.1/nginx_status"
curl=/usr/bin/curl
# 检测nginx进程是否存在
function ping {
/sbin/pidof nginx | wc -l
}
# 检测nginx性能
function active {
$curl $url 2>/dev/null| grep 'Active' | awk '{print $NF}'
}
function reading {
$curl $url 2>/dev/null| grep 'Reading' | awk '{print $2}'
}
function writing {
$curl $url 2>/dev/null| grep 'Writing' | awk '{print $4}'
}
function waiting {
$curl $url 2>/dev/null| grep 'Waiting' | awk '{print $6}'
}
function accepts {
$curl $url 2>/dev/null| awk NR==3 | awk '{print $1}'
}
function handled {
$curl $url 2>/dev/null| awk NR==3 | awk '{print $2}'
}
function requests {
$curl $url 2>/dev/null| awk NR==3 | awk '{print $3}'
}
$1
chmod +x nginx_status.sh ; ./nginx_status.sh
bash nginx_status.sh
sh nginx_status.sh
#date +%Y-%m-%d ; date +%y-%m-%d 年月日
[root@linux2019_3 ~]# date +%Y-%m-%d ; date +%y-%m-%d
2019-03-06
19-03-06
#date +%H:%M:%S = date +%T 时间
[root@linux2019_3 ~]# date +%H:%M:%S
11:59:51
[root@linux2019_3 ~]# date +%T
11:59:57
#date +%s 时间戳
[root@linux2019_3 ~]# date +%s
1551844832
#date -d @1551844944
[root@linux2019_3 ~]# date -d @1551844944
2019年 03月 06日 星期三 12:02:24 CST
#date -d "+1day" 一天后
[root@linux2019_3 ~]# date -d "+1day"
2019年 03月 07日 星期四 12:03:26 CST
#date -d "-1 day" 一天前
[root@linux2019_3 ~]# date -d "-1day"
2019年 03月 05日 星期二 12:03:48 CST
#date -d "-1 month" 一月前
[root@linux2019_3 ~]# date -d "+1month"
2019年 04月 06日 星期六 12:04:03 CST
#date -d "-1 min" 一分钟前
[root@linux2019_3 ~]# date -d "-min"
2019年 03月 06日 星期三 12:05:30 CST
#date +%w, date +%W 星期
[root@linux2019_3 ~]# date +%W
09 #今年的第9周
[root@linux2019_3 ~]# date +%w
3 #本周周三
当脚本中使用某个字符串较频繁并且字符串长度很长时就可以使用变量代替
[root@linux2019_3 ~]# a=1+2;echo $a
1+2
[root@linux2019_3 ~]# a=1;b=2; c=$(($a+$b)); echo $c
3
[root@linux2019_3 ~]# a=1;b=2;c=$[$a+$b] ;echo $c
3
# c=$(($a+$b))等效于$[$a+$b]
-eq—等于
-ne—不等于
-gt—大于
-lt—小于
-ge—大于等于
-le—小于等于
&&—逻辑与
||—逻辑或
!—逻辑非
[root@linux2019 ~]# ll abc
ls: 无法访问abc: 没有那个文件或目录
[root@linux2019 ~]# if ! ls abc &>/dev/null ;then echo zhilin is wrong; fi
zhilin is wrong
# !取反
# &>/dev/null 不管结果如何,丢弃结果
root用户对文件的读写比较特殊,即使一个文件没有给root用户读或者写的权限,root用户照样可以读或者写,但是执行的权限是正常的
[root@linux2019 ~]# grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@linux2019 ~]# grep -q root /etc/passwd ;echo $?
0
[root@linux2019 ~]# grep -q roottt /etc/passwd ;echo $?
1