2018-05-29 Linux学习

20.1 Shell脚本介绍

shell是什么

shell是一种脚本语言  aming_linux  blog.lishiming.net
可以使用逻辑判断、循环等语法
可以自定义函数
shell是系统命令的集合
shell脚本可以实现自动化运维,能大大增加我们的运维效率

20.2 Shell脚本结构和执行

开头需要加#!/bin/bash
以#开头的行作为解释说明
脚本的名字以.sh结尾,用于区分这是一个shell脚本
执行方法有两种
chmod +x 1.sh; ./1.sh
bash 1.sh
查看脚本执行过程 bash -x 1.sh
查看脚本是否语法错误  bash -n 1.sh

20.3 date命令用法

date  +%Y-%m-%d, date +%y-%m-%d 年月日
date  +%H:%M:%S = date +%T 时间
date +%s  时间戳
date -d @1504620492
date -d "+1day"  一天后
date -d "-1 day"  一天前
date -d "-1 month" 一月前
date -d "-1 min"  一分钟前
date +%w, date +%W 星期

操作过程

[root@linux-01 ~]# date
2018年 04月 22日 星期日 21:12:09 CST
[root@linux-01 ~]# date +%Y
2018
[root@linux-01 ~]# date +%y
18
[root@linux-01 ~]# date +%m
04
[root@linux-01 ~]# date +%M
12
[root@linux-01 ~]# date +%d
22
[root@linux-01 ~]# date +%D
04/22/18
[root@linux-01 ~]# date +%Y%m%d
20180422
[root@linux-01 ~]# date +%F
2018-04-22

[root@linux-01 ~]# date +%H
21
[root@linux-01 ~]# date +%s
1524402829
[root@linux-01 ~]# date +%S
54

[root@linux-01 ~]# date +%T
21:15:14
[root@linux-01 ~]# date +%h
4月
[root@linux-01 ~]# date +%w
0
[root@linux-01 ~]# date +%W
16

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

[root@linux-01 ~]# LANG=en_US
[root@linux-01 ~]# date
Sun Apr 22 21:25:46 CST 2018

[root@linux-01 ~]# date -d "-1 day"
Sat Apr 21 21:26:18 CST 2018
[root@linux-01 ~]# date -d "-1 day" +%F
2018-04-21
[root@linux-01 ~]# date -d "-1 month"
Thu Mar 22 21:26:36 CST 2018
[root@linux-01 ~]# date -d "-1 year"
Sat Apr 22 21:27:56 CST 2017
[root@linux-01 ~]# date -d "-1 hour"
Sun Apr 22 20:28:05 CST 2018
[root@linux-01 ~]# date -d "-1 hour" +%F
2018-04-22
[root@linux-01 ~]# date -d "-1 hour" +%T
20:29:01

[root@linux-01 ~]# date +%s
1524403788
[root@linux-01 ~]# date -d @1524403788
Sun Apr 22 21:29:48 CST 2018

[root@linux-01 ~]# date +%s -d "2018-04-22 21:29:48"
1524403788

20.4 Shell脚本中的变量

当脚本中使用某个字符串较频繁并且字符串长度很长时就应该使用变量代替
使用条件语句时,常使用变量    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] 

猜你喜欢

转载自blog.51cto.com/9298822/2121933