shell脚本是一些命令的集合
shell的创建和执行:
cd /usr/local/sbin/
vim firsh.sh
#! /bin/bash
date
echo "hello world"
执行:
sh firsh.sh
2019年 06月 17日 星期一 13:17:15 CST
hello world
./firsh.sh
-bash: ./firsh.sh: 权限不够
chmod +x firsh.sh
./firsh.sh
2019年 06月 17日 星期一 13:20:46 CST
hello world
看执行过程
sh -x firsh.sh
+ date
2019年 06月 17日 星期一 13:22:21 CST
+ echo 'hello world'
hello world
date命令:
date +%Y:表示以四位数格式打印年份
date +%Y
2019
date +%y:两位数格式打印年份
date +%y
19
date +%m:表示月份
date +%m
06
date +%d:表示日期
date +%d
17
date +%H:表示小时
date +%M:表示分钟
date +%S:表示秒
date +%w:表示星期几,0表示星期天
比如:
date +"%Y-%m-%d %H-%M-%S"
2019-06-17 13-50-55
一天前的日期:
date -d "-1 day" +%d
16
一小时前:
date -d "-1 hour" +%H
12
一分钟以前:
date -d "-1 min" +%M
03
2.shell中的脚本变量:
vim firsh2.sh
#! /bin/bash
d=`date +%H:%M:%S`
echo "The script begin at $d."
echo "Now we'll sleep 2 seconds."
sleep 2
d1=`date +%H:%M:%S`
echo "The script end at $d1"
vim firsh2.sh
[root@ligenkelong sbin]# sh firsh2.sh
The script begin at 14:33:43.
Now we'll sleep 2 seconds.
The script end at 14:33:45
[root@ligenkelong sbin]#
shell中的逻辑判断:
if....;then
.....
fi
或者
if....;then
....
else
.....
fi
或者:
if.....;then
....
elif......;then
.....
else
.....
fi
&&:表示并且
|| :表示或者
-lt:小于
-gt:大于
-ge:大于等于
-le:小于等于
-eq:等于
-ne:不等于
文件目录属性判断:
#!/bin/bash
f="/tmp/ligen"
if [ -x $f ]
then
echo $f readable
else
echo "no"
fi
&&:当前面的正确是才会执行后面的
|| :当前面的错误时才会执行后面的
#!/bin/bash
f="/tmp/ligen"
# [ -f $f ] && rm -f $f
[ -f $f ] || touch $f
if的特殊用法:
case:
for循环:
for
do
done
while循环:
break:用在循环语句里
contunue:结束本次循环
exit:退出整个脚本
数组: