一、shell脚本介绍

1、shell 是一只能够脚本语言

2、可以使用逻辑判断,循环等语法

3、可以自定义函数

4、shell 是系统命令的集合

5、shell 可以实现自动化运维,提升运维效率。

二、shell 脚本的结构和执行方法

1、首行以  #!/bin/bash 开始,表示该文件是用的是bash语法。

2、#开头的行作为解释说明,表示该行命令的作用或者其他信息。

3、脚本以.sh结尾,用于区分这是一个shell脚本

4、执行方法

sh test.sh 

chmod +x test.sh ;  ./test.sh

5、查看脚本执行过程  sh -x test.sh   -x 显示shell脚本执行的过程

[root@localhost ~]# sh -x test.sh
+ read -p 'Please input a number:' a
Please input a number:1
+ read -p 'Please input another number:' b
Please input another number:2
+ sum=3
+ echo 'sum is 3'
sum is 3
[root@localhost ~]#

6、查看脚本语法是否错误  sh -n test.sh  -n 判断脚本语法是否有错误

如果没有输出,说明没有语法错误

如果有报错,说明语法有错误

三、date 命令的用法

1、date  显示时间

[root@localhost ~]# date
2018年 04月 17日 星期二 19:52:16 CST
[root@localhost ~]#

2、年的表示

[root@localhost ~]# date +%Y          #以四位数字格式打印年份
2018
[root@localhost ~]# date +%y           #以二位数字格式打印年份
18

3、月的表示

[root@localhost ~]# date +%m
04

4、分钟

 [root@localhost ~]# date +%M

03

5、日期

[root@localhost ~]# date +%d
17

6、年月日

[root@localhost ~]# date +%D
04/17/18

[root@localhost ~]# date +%Y-%m-%d
2018-04-17

[root@localhost ~]# date +%F
2018-04-17

7、小时

[root@localhost ~]# date +%H
21

8、秒

[root@localhost ~]# date +%S
54

9、时间戳

[root@localhost ~]# date +%s
1523970626

10、时间表示

[root@localhost ~]# date +%H:%M:%S
21:12:36
[root@localhost ~]# date +%T
21:12:41

11、周几的表示

[root@localhost ~]# date +%w
2

12、一年中的第几周

[root@localhost ~]# date +%W
16

13、日历

[root@localhost ~]# 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

 14、前一天,前一个月 ,前一年,前一小时

[root@localhost ~]# date -d "-1 day" +%F
2018-04-16
[root@localhost ~]# date -d "-1 month" +%F
2018-03-17
[root@localhost ~]# date -d "-1 year" +%F
2017-04-17
[root@localhost ~]# date -d "-1 hour" +%T
20:25:29

15、时间戳换算

[root@localhost ~]# date +%s
1523971613
[root@localhost ~]# date -d @1523971613
2018年 04月 17日 星期二 21:26:53 CST
[root@localhost ~]# date -d @1523971613
2018年 04月 17日 星期二 21:26:53 CST
[root@localhost ~]# date +%s -d "2018-04-17"
1523894400

四、shell脚本中的变量

1、当脚本中使用某个字符串比较频繁或字符串过长时就应该用变量代替。

2、使用条件语句时,常用变量

if [ $sum -eq 3 ]
then
echo "ok"
fi

3、应用某个命令结果时,用变量替代: n=cat 1.txt |wc -l

4、和用户交互,也使用变量代替

read -p "Please input a number:" a

read -p "Please input another number:" b

5、数学运算

read -p "Please input a number:" a
read -p "Please input another number:" b
sum=$[$a+$b]

posted on 2018-04-17 21:49  天梭  阅读(121)  评论(0编辑  收藏  举报