• shell是一种脚本语言 aming_linux blog.lishiming.netlinux
• 可使用逻辑判断、循环等语法nginx
• 能够自定义函数shell
• shell是系统命令的集合vim
• shell脚本能够实现自动化运维,能大大增长咱们的运维效率bash
开头须要加#!/bin/bash运维
[root@linux-5 ~]# mkdir shell [root@linux-5 ~]# cd shell [root@linux-5 shell]# vim lem01.sh #!/bin/bash
写shell脚本,第一行必须写#! /bin/bash,固定格式,做用是指定脚本中命令所需的解释器,脚本如果在当台机器上去执行,能够不加这一行也不要紧,由于它知道下面若干条的命令能在这台机器上去执行,去解析,一般都是 /bin/bash 解释器来执行的函数
/bin/bash也是一条命令, /bin/bash 和 /bin/sh 是同一个文件spa
[root@linux-5 shell]# ll /bin/bash -rwxr-xr-x. 1 root root 960472 8月 3 2017 /bin/bash [root@linux-5 shell]# ll /bin/sh lrwxrwxrwx. 1 root root 4 3月 4 05:42 /bin/sh -> bash
lem01.sh文件内容就是被/bin/bash所解析的.net
若shell脚本中首行没有/bin/bash ,可使用 /bin/bash lem01.sh去执行日志
以#开头的行做为解释说明,除了脚本首行的特殊性之外,如果在shell脚本中的第二行写入#号开头的行, 就表示解释说明的做用
一种是sh lem01.sh运行shell脚本
另外一种方法
先 chmod a+x lem01.sh 给文件加一个执行权限
再 ./lem01.sh 去执行
[root@linux-5 shell]# chmod a+x lem01.sh [root@linux-5 shell]# ./lem01.sh
这里的 ./ 就至关于一个相对路径,相对当前一个路径
也可使用绝对路径去执行脚本 /root/shell/lem01.sh ,其实就是找到这个文件去执行
执行时加入-x,-x就是显示脚本执行的过程
[root@linux-5 shell]# sh -x lem01.sh + w 11:36:51 up 33 min, 1 user, load average: 0.01, 0.02, 0.05 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT root pts/0 192.168.88.1 11:06 3.00s 0.04s 0.00s sh -x lem01.sh
每个加号,表示一个操做步骤
执行时加入-n,-n就是检测脚本执行是否有语法错误
[root@linux-5 shell]# sh -n lem01.sh [root@linux-5 shell]#
如果没有任何的输出,那么脚本则没有错误
date命令,能够显示当前系统时间日期
[root@linux-5 shell]# date 2018年 07月 12日 星期四 11:58:05 CST
date命令,在shell中用处很是大;对文件后缀增长一个时间,以便后期管理
[root@linux-5 shell]# date +%Y 2018 //四位的年 [root@linux-5 shell]# date +%y 18 //两位的年 [root@linux-5 shell]# date +%m 07 //月份 [root@linux-5 shell]# date +%h 7月 //月份 [root@linux-5 shell]# date +%w 4 //表示周几 [root@linux-5 shell]# date +%W 28 //今年的第几周,今年的第28周 [root@linux-5 shell]# date +%d 12 //日期 [root@linux-5 shell]# date +%D 07/12/18 //直接标记年月日,不过格式比较特殊 [root@linux-5 shell]# date +%Y%m%d 20180711 //年月日 [root@linux-5 shell]# date +%F 2018-07-11 //年月日,这种带横杠的
[root@linux-5 shell]# date +%H 12 //小时 [root@linux-5 shell]# date +%M 32 //分钟 [root@linux-5 shell]# date +%S 53 //秒 [root@linux-5 shell]# date +%T 13:41:37 //总体时间 [root@linux-5 shell]# date +%s 1531322044 //这是一个时间戳,距离1970年1月1日0点0分总共过去多少秒
[root@linux-5 shell]# cal 七月 2018 日 一 二 三 四 五 六 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
在作nginx日志切割的时候,到了凌晨切割日志,到了零点零分切割的日志是前一天的日志。因此把日志加一个时间标记的话,应标记为昨天的日期
减号- 表示以前的日期,加号 + 表示从今日后的日期
date -d "-1 day" +%F ##显示前一天的日期 date -d "-1 month" +%F ##显示上个月的日期 date -d "-1 years" +%F ##显示上一年的日期 date -d "+1 hour" +%T ##显示下一小时
[root@linux-5 shell]# date +%s -d "2018-07-12 13:48:11" 1531374491 [root@linux-5 shell]# date -d @1531374491 2018年 07月 12日 星期四 13:48:11 CST
•当脚本中使用某个字符串较频繁而且字符串长度很长时就应该使用变量代替
• 使用条件语句时,常使用变量 if [ $a -gt 1 ]; then ... ; fi
• 引用某个命令的结果时,用变量替代 n=`wc -l 1.txt`
• 写和用户交互的脚本时,变量也是必不可少的 read -p "Input a number: " n; echo $n 若是没写这个n,能够直接使用$REPLY
• 内置变量 $0, $1, $2… $0表示脚本自己,$1 第一个参数,$2 第二个 .... $#表示参数个数
• 数学运算a=1;b=2; c=$(($a+$b))或者$[$a+$b]