12月27日
20.1 shell脚本介绍
shell是什么
· shell是一种脚本语言 aming_linux blog.lishiming.net
· 可以使用逻辑判断、循环等语法
· 可以自定义函数
· shell是系统命令的集合
· shell脚本可以实现自动化运维,能大大增加我们的运维效率
20.2 shell脚本结构和执行
shell脚本结构和执行方法
· 开头需要加#!/bin/bash
· 以#开头的行作为解释说明(作者,作用什么的)
· 脚本的名字以.sh结尾,用于区分这是一个shell脚本
· 执行方法有两种
chmod +x 1.sh; ./1.sh
bash 1.sh
· 查看脚本执行过程 bash -x 1.sh // sh -x 1.sh
· 查看脚本是否语法错误 bash -n 1.sh//sh -n 1.sh
20.3 date命令用法
date命令的用法
· date +%Y-%m-%d, date +%y-%m-%d 年月日
+%Y(xxxx年)
+%y(xx年)
+%m(月份)
+%F (2018-12-27)
· date +%H:%M:%S = date +%T 时间
+% M(分钟)
+%H(小时)
+%h (英文月)
+%S(秒)
+%T (时:分:秒)
· date +%s 时间戳 (距离1970年1月1日0点0分到现在过去多少秒)
· date -d @1504620492
· date -d "+1day" 一天后
· date -d "-1 day" 一天前
· date -d "-1 month" 一月前
· date -d "-1 min" 一分钟前
· date +%w, date +%W 星期
· date -d “-1 year”+%F 一年前(2017-12-27)
· date -d“-1 hour” +%T 一小时前
+%w (周几)
+%W (今年的第几周)
· cal 日历
20.4 shell脚本中的变量
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]