第二十章 Shell编程(上)
20.1 Shell脚本介绍
20.2 Shell脚本结构和执行
20.3 date命令用法
Y年 m月 d日
[[email protected] shell]# date +%Y%m%d
20181026
H小时 M分钟 S秒
[[email protected] shell]# date +%H-%M-%S
03-56-41
F 代表年月日
[[email protected] shell]# date +%F
2018-10-26
T 代表小时 分钟 秒
[[email protected] shell]# date +%T
03:25:34
s(小写)时间戳
把当前时间转换成时间戳
[[email protected] shell]# date +%s
1540539856
把时间戳转换成时间
[[email protected] shell]# date -d @1540539856
Fri Oct 26 03:44:16 EDT 2018
把以前的时间转换成时间戳
[[email protected] shell]# date +%s -d "2017-10-26 03:44:16"
1509003856
把以前的时间戳转换成时间
[[email protected] shell]# date -d @1509003856
Thu Oct 26 03:44:16 EDT 2017
w 周(0--6)0代表周日
[[email protected] shell]# date +%w
5
W(大写) 今年的第几周
[[email protected] shell]# date +%W
43
-1 day 一天以前
date -d "-1 day" +%F
一小时以前
date -d "-1 hour"
一分钟以前
date -d "-1 min"
-1 month 一月以前
date -d "-1 month" +%F
-1 year 一年以前
date -d "-1 year" +%F
20.4 Shell脚本中的变量
20.5 Shell脚本中的逻辑判断
-gt 大于 -lt 小于 -ge 大于等于 -le 小于等于 -eq 等于 -ne 不等于
[ $a -gt 5 ] 注意方括号里面有空格
&& 并且 前面的成立的时候才会执行后面的
|| 或者 前面不成立的时候才会执行后面的
20.6 文件目录属性判断
20.7 if特殊用法
-w 精确匹配一个词 -q 匹配到不显示 !没有过滤到这个用户
20.8 case判断(上)
案例
#!/bin/bash
read -p "Please input a number: " n
if [ -z "$n" ]
then
echo "Please input a number."
exit 1
fi
n1=`echo $n|sed 's/[0-9]//g'`
if [ -n "$n1" ]
then
echo "Please input a number."
exit 1
fi
if [ $n -lt 60 ] && [ $n -ge 0 ]
then
tag=1
elif [ $n -ge 60 ] && [ $n -lt 80 ]
then
tag=2
elif [ $n -ge 80 ] && [ $n -lt 90 ]
then
tag=3
elif [ $n -ge 90 ] && [ $n -le 100 ]
then
tag=4
else
tag=0
fi
case $tag in
1)
echo "no good"
;;
2)
echo "good"
;;
3)
echo "very good"
;;
4)
echo "great"
;;
*)
echo "The number range is 0-100."
;;
esac
20.10 for循环
ls 会以空隔为分隔符,注意!
20.11 while循环(上)
20.12 while循环(下)
20.13 break跳出循环
20.14 continue结束本次循环
执行过程
[[email protected] shell]# sh -x continue.sh
++ seq 1 5
+ for i in '`seq 1 5`'
+ echo 1
1
+ '[' 1 -eq 3 ']'
+ echo 1
1
+ for i in '`seq 1 5`'
+ echo 2
2
+ '[' 2 -eq 3 ']'
+ echo 2
2
+ for i in '`seq 1 5`'
+ echo 3
3
+ '[' 3 -eq 3 ']'
+ continue
+ for i in '`seq 1 5`'
+ echo 4
4
+ '[' 4 -eq 3 ']'
+ echo 4
4
+ for i in '`seq 1 5`'
+ echo 5
5
+ '[' 5 -eq 3 ']'
+ echo 5
5
+ echo ok
ok
20.15 exit退出整个脚本