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]
来源: http://www.bubuko.com/infodetail-2623457.html