Shell Script,Shell脚本与Windows/Dos下的批处理类似,也就是用各种命令预先放入到一个文件中,方便一次性执行的一个程序文件,主要是方便管理员进行设置或者管理用的。可是它比Windows下的批处理更强大,比用其余编程程序编辑的程序效率更高,它使用了Linux/Unix下的命令。python
换一种说法也就是,shell script是利用shell的功能所写的一个程序,这个程序是使用纯文本文件,将一些shell的语法与指令写在里面,而后用正规表示法,管道命令以及数据流重导向等功能,以达到咱们所想要的处理目的。linux
更明白地来讲,shell script就像早期dos年代的.bat,最简单的功能就是将许多指令汇整写一块儿,让使用者很容易地就可以一个操做执行多个命令,而shell script更是提供了数组,循环,条件以及逻辑判断等重要功能,让使用者能够直接以shell来写程序,而没必要使用相似C程序语言等传统程序编写的语法。nginx
shell脚本能够实现自动化运维,能大大增长咱们的运维效率shell
Shell脚本的第一行必须是:#!/bin/bash,"#!" 是一个约定的标记,后面跟着的/bin/bash是告诉系统这个脚本须要使用/bin/bash解释器来执行,即便用哪种Shell。编程
简单来讲就是告诉系统这是一个什么语言写的脚本,是python是shell或者是其余的脚本语言所写的,而后系统才能使用相应的解释器去执行这个脚本。不过若是这个shell脚本是在本机执行的话,却是能够省略掉:#!/bin/bash,由于可以识别本机的命令,可是若是到另外一台机器就不必定可以执行了,因此文件的第一行才要写这样的声明。数组
Shell脚本的文件名称是以.sh为后缀,用于区分这是一个shell脚本,shell中的注释符是井号“#”,和其余编程语言同样,注释的那一行内容不会被解释器执行,可是要注意区别“#!”和“#”,前者是标记,后者才是注释符。bash
编写第一个脚本:运维
#!/bin/bash echo "hello shell!" w ls
执行脚本的方法有三种:编程语言
第二种执行方法是给这个Hello.sh的脚本文件加上了可执行权限,因此能够当作一个二进制文件直接执行日志
sh和bash其实是同一个命令,由于sh是bash的软链接文件:
查看脚本执行过程 bash -x studyshell01.sh ,每个“+”表明执行的命令,后面跟着命令的执行结果。
查看脚本是否语法错误 bash -n studyshell01.sh,没有输出表明没有错误,不然直接输出错误:
可是要注意的是,这只是检查脚本的语法错误,若是你系统命令写错了,是不会被检查到的。
1.date命令,会显示当前系统时间日期
[root@yolks3 shell]# date 2018年 09月 13日 星期四 23:45:07 CST
2.date命令,在shell中用处很是大;对文件后缀增长一个时间,以便后期管理 3.date +%Y-%m-%d, date +%y-%m-%d 年月日
[root@yolks3 shell]# LANG=en #临时切换为英文显示 [root@yolks3 shell]# date Thu Sep 13 23:46:51 CST 2018 //英文日期 [root@yolks3 shell]# date +%Y 2018 四位的年 [root@yolks3 shell]# date +%y 18 两位的年 [root@yolks3 shell]# date +%m 09 月份 [root@yolks3 shell]# date +%M 47 分钟 [root@yolks3 shell]# date +%d 13 日期 [root@yolks3 shell]# date +%D 09/13/18 特殊格式的年月日 [root@yolks3 shell]# date +%Y%m%d 20180913 组合年月日 [root@yolks3 shell]# date +%Y-%m-%d 2018-09-13 拼接年-月-日 [root@yolks3 shell]# date +%F 2018-09-13 格式化后的年-月-日 [root@yolks3 shell]# date +%H 23 时 [root@yolks3 shell]# date +%s 1536853846 时间戳,表示距离1970年总共过去了多少秒 [root@yolks3 shell]# date +%S 57 秒 [root@yolks3 shell]# date +%T 23:53:26 时间:时:分:秒
4.常见时间单位
[root@yolks3 shell]# date +%w 4 今天周几 [root@yolks3 shell]# date +%W 37 本周是今年第多少周
5.日历
[root@yolks3 shell]# cal September 2018 Su Mo Tu We Th Fr Sa 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
6.标记以前或以后的时间
需求:在作nginx日志切割的时候,到了凌晨切割日志,到了零点零分切割的日志是前一天的日志。因此把日志加一个时间标记的话,应标记为昨天的日期
示例:
[root@yolks3 shell]# date -d "-1 day" Wed Sep 12 23:59:16 CST 2018 [root@yolks3 shell]# date -d "-1 day" +%F 2018-09-12 [root@yolks3 shell]# date -d "-1 month" +%F 2018-08-13 [root@yolks3 shell]# date -d "-1 months" +%F 2018-08-14
7.时间戳 : date +%s
另外一种表现方法,表示时间戳 : date -d @1504620492 就是@后跟时间戳
[root@yolks3 shell]# date +%s 1536854629 [root@yolks3 shell]# date -d @1536854629 Fri Sep 14 00:03:49 CST 2018
8.若想在linux系统中,把具体的日期换算成时间戳的时候,可使用date +%s -d "2018-09-14 00:06:19"
[root@yolks3 shell]# date +%F" "%T 2018-09-14 00:06:19 显示年月日时分秒 [root@yolks3 shell]# date +%s -d "2018-09-14 00:06:19" 1536854779 转换时间戳