20.1 shell脚本介绍
- shell是一种脚本语言
- 能够使用逻辑判断、循环等语法
- 能够自定义函数
- 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 年月日shell
[root@zhangjin-120:~/shells]#date +%Y-%m-%d 2019-01-09
bash
-
date +%H:%M:%S = date +%T 时间运维
[root@zhangjin-120:~/shells]#date +%T 11:43:57
函数
[root@zhangjin-120:~/shells]#date +%H:%M:$S 11:44:
code
-
date +%s 时间戳字符串
[root@zhangjin-120:~/shells]#date +%s 1547005590
数学
-
date -d "+1day" 一天后it
[root@zhangjin-120:~/shells]#date -d "+1day" 2019年 01月 10日 星期四 11:48:15 CST
自动化
-
date -d "-1 day" 一天前for循环
[root@zhangjin-120:~/shells]#date -d "-1day" 2019年 01月 08日 星期二 11:50:25 CST
-
date -d "-1 month" 一月前
[root@zhangjin-120:~/shells]#date -d "-1 month" 2018年 12月 09日 星期日 11:51:28 CST
-
date -d "-1 min" 一分钟前
[root@zhangjin-120:~/shells]#date -d "-1 min" 2019年 01月 09日 星期三 11:51:12 CST
-
date +%w, date +%W 星期
[root@zhangjin-120:~/shells]#date +%w
3
[root@zhangjin-120:~/shells]#date +%W
01
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]
20.5 shell脚本中的逻辑判断
- 格式1:if 条件 ; then 语句; fi
- 格式2:if 条件; then 语句; else 语句; fi
- 格式3:if …; then … ;elif …; then …; else …; fi
- 逻辑判断表达式:if [ $a -gt $b ]; if [ $a -lt 5 ]; if [ $b -eq 10 ]等
-gt (>); -lt(<); -ge(>=); -le(<=);-eq(==); -ne(!=) 注意空格
- 能够使用 && || 结合多个条件
- if [ $a -gt 5 ] && [ $a -lt 10 ]; then
- if [ $b -gt 5 ] || [ $b -lt 3 ]; then
20.6 文件目录属性判断
- [ -f file ] 判断是不是普通文件,且存在
- [ -d file ] 判断是不是目录,且存在
- [ -e file ] 判断文件或目录是否存在
- [ -r file ] 判断文件是否可读
- [ -w file ] 判断文件是否可写
- [ -x file ] 判断文件是否可执行
20.7 if特殊用法
- if [ -z "$a" ] 这个表示当变量a的值为空时会怎么样
- if [ -n "$a" ] 表示当变量a的值不为空
- if grep -q '123' 1.txt; then 表示若是1.txt中含有'123'的行时会怎么样
- if [ ! -e file ]; then 表示文件不存在时会怎么样
- if (($a<1)); then …等同于 if [ $a -lt 1 ]; then… [ ] 中不能使用<,>,==,!=,>=,<=这样的符号
20.8/20.9 case判断
格式:
case 变量名 in
value1)
command
;;
value2)
command
;;
*)
command
;;
esac
在case程序中,能够在条件中使用|,表示或的意思, 好比
1|2)
command
;;
20.10 for循环
语法:for 变量名 in 条件; do …; done
20.11/20.12 while循环
语法 while 条件; do … ; done
20.13 break跳出循环
20.14 continue结束本次循环
忽略continue之下的代码,直接进行下一次循环
20.15 exit退出整个脚本