3、学会date命令的用法
date +%Y-%m-%d date +%y-%m-%d 年月日
date +%Y-%m-%d = date +%F 年月日
date +%H:%M:%S = date +%T 时间
date +%s 时间戳
date -d @1434248742 根据时间戳算出当前时间
date -d "+1day" 一天后 date -d "-1day" 一天前
date -d "-1month" 一月前
date -d “-1min” 一分钟前
date +%w date +%W 星期
实验练习:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[iyunv@localhost shell]# date +%y
15
[iyunv@localhost shell]# date +%Y
2015
[iyunv@localhost shell]# date +%m
06
[iyunv@localhost shell]# date +%d
16
[iyunv@localhost shell]# date +%H
14
[iyunv@localhost shell]# date +%M
01
[iyunv@localhost shell]# date +%S
54
从1970年 01月01日0点0分开始算起到现在多少秒;
1
2
3
4
[iyunv@localhost shell]# date +%s
1434434874
[iyunv@localhost shell]# date -d @1434434874
2015年 06月 16日 星期二 14:07:54 CST
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 (greater than)
小于< lt (less than)
大于等于 >= ge
小于等于 <= le
等于 ==eq (equal)
不等于 != ne
实验练习:
1
2
3
4
5
6
7
8
9
[iyunv@localhost shell]# cat if.sh
#!/bin/bash
#if判断语句,条件为真,打印true;
if :
then
echo true
fi
[iyunv@localhost shell]# sh if.sh
true
if判断语句2;
1
2
3
4
5
6
7
8
9
10
11
12
13
[iyunv@localhost shell]# cat if2.sh
#!/bin/bash
#if判断语句,条件为真,返回true;
if [ 1 == 1 ]
then
echo "true"
fi
[iyunv@localhost shell]# sh -x if2.sh
+ '[' 1 == 1 ']'
+ echo true
true
[iyunv@localhost shell]# sh if2.sh
true
if判断语句3;
1
2
3
4
5
6
7
8
9
10
11
[iyunv@localhost shell]# cat if3.sh
#!/bin/bash
#if判断语句,条件为真返回true,条件为假,返回false;
if [ "1" == "2" ]
then
echo "true"
else
echo "false"
fi
[iyunv@localhost shell]# sh if3.sh
false
变量,进行比较
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[iyunv@localhost shell]# cat if4.sh
#!/bin/bash
#if判断语句,变量进行比较;
a=1
if [ "$a" == "2" ]
then
echo "true"
else
echo "false"
fi
[iyunv@localhost shell]# sh -x if4.sh
+ a=1
+ '[' 1 == 2 ']'
+ echo false
false
多个判断要加elif
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[iyunv@localhost shell]# cat if5.sh
#!/bin/bash
#if判断语句,多个判断使用elif;
a=1
if [ "$a" == "2" ]
then
echo "true"
elif [ "$a" -lt 10 ]
then
echo "no false"
else
echo "false"
fi
[iyunv@localhost shell]# sh if5.sh
no false
[ $a -lt 3 ] 也可以这样代替 (($a<3));使用方括号请一定注意空格;
1
2
3
4
[iyunv@localhost shell]# a=1;if(($a<3)); then echo OK;fi
OK
[iyunv@localhost shell]# a=1;if [ $a -lt 3 ]; then echo OK;fi
OK
&& 并且 前面的执行成功后才执行后面的; || 或者 前面的执行不成功执行后面的;
1
2
3
4
5
[iyunv@localhost shell]# a=5
[iyunv@localhost shell]# if [ $a -lt 10 ]&&[ $a -gt 2 ];then echo OK;fi
OK
[iyunv@localhost shell]# if [ $a -lt 10 ]||[ $a -gt 2 ];then echo OK;fi
OK
奇数偶数判断,输入的数字除以2,余数为0为偶数,非0为奇数;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[iyunv@yonglinux shell]# cat 4.sh
#!/bin/bash
read -p "enter a number:" n
n1=$[$n%2]
if [ $n1 -eq 0 ]
then
echo "你输入的数字是偶数"
else
echo "你输入的数字是奇数"
fi
[iyunv@yonglinux shell]# sh 4.sh
enter a number:23
你输入的数字是奇数
[iyunv@yonglinux shell]# sh 4.sh
enter a number:90
你输入的数字是偶数