一、crontab配置
1、命令功能
通过crontab 命令,我们可以在固定的间隔时间执行指定的系统指令或 shell script脚本。时间间隔的单位可以是分钟、小时、日、月、周及以上的任意组合。这个命令非常适合周期性的日志分析或数据备份等工作。
2、安装
yum install crontabs
服务操作说明:
service crond start ## 启动服务
service crond stop ## 关闭服务
service crond restart ## 重启服务
service crond reload ## 重新载入配置
3、修改任务计划的命令格式
crontab [-u user] file
crontab [-u user] [ -e | -l | -r ]
必掌握:
crontab -l [-u user] ## 列出用户目前的crontab.
crontab -e [-u user] ## 编辑用户目前的crontab.
crontab -e
*/1 * * * * echo “haha” >> /root/haha.txt
/1 * * * * echo “xixi” >> /root/xixi.txt
4、调度配置
基本格式 :
* * * * * command
分 时 日 月 周 命令
第1列表示分钟1~59 每分钟用或者 */1表示
第2列表示小时0~23(0表示0点) 7-9表示:7点到9点之间
第3列表示日期1~31
第4列表示月份1~12
第5列标识号星期0~6(0表示星期天)
第6列要运行的命令
二、shell编程
**1.基本格式:**代码写在普通文本文件中,通常以 .sh为后缀名:vi hello.sh
执行脚本:sh hello.sh
或给脚本添加x权限,直接执行:chmod 755 hello.sh
2.基本语法
set命令查看变量
3.算数表达式运算
用expr
1 .分步计算
赋值:
[root@hadoop2 home]# S=expr 2 + 3
[root@hadoop2 home]# B=expr $S \* 4
## *号需要转义
[root@hadoop2 home]# echo $B
2.一步完成计算
expr expr 2 + 3
* 4
*用(())
((1+2))
(((2+3)*4))
count=1
((count++))
echo $count
报错
-bash: syntax error near unexpected token `(’
但是要想取到运算结果,需要用 $ 引用a=$((1+2))
用 $ []
a=$[1+2]
echo $a
用let
i=1
let i++
4.流程控制
1、语法格式
if condition
then
statements
[elif condition
then statements. …]
[else
statements ]
fi
举例
#!/bin/bash
read -p “please input your name:” NAME ## read命令用于从控制台读取输入数据
printf ‘%s\n’ $NAME
if [ $NAME = ljr ]
then
echo “hello ${NAME}, welcome !”
elif [ $NAME = zww]
then
echo “hello ${NAME}, welcome !”
else
echo “pig, get out here !”
fi
判断条件:
[root@shizhan01 scripts]# if [ a = b ];then echo ok;else echo notok;fi
notok
[root@shizhan01 scripts]# if [ a=b ];then echo ok;else echo notok;fi
ok
case语法(用的多)
case $1 in
start)
echo “starting”
;;
stop)
echo “stoping”
;;
*)
echo “Usage: {start|stop}”
esac
5.函数使用
#!/bin/bash
fun1.sh
funWithParam(){
echo “第一个参数为 $1 !”
echo “第二个参数为 $2 !”
echo “第十个参数为 $10 !”
echo “第十个参数为 ${10} !”
echo “第十一个参数为 ${11} !”
echo “参数总数有 $# 个!”
echo “作为一个字符串输出所有参数 $* !”
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73
6.函数返回值
#!/bin/bash
#fun2.sh
funWithReturn(){
echo “这个函数会对输入的两个数字进行相加运算…”
echo "输入第一个数字: "
read aNum
echo "输入第二个数字: "
read anotherNum
echo “两个数字分别为 $aNum 和 $anotherNum !”
return
(
(
((
((aNum+$anotherNum))
}
funWithReturn
echo “输入的两个数字之和为 $? !”
7.跨脚本调用函数
#!/bin/bash
fun_other.sh
. /root/fun1.sh ## 注: . 和 / 之间有空格
#或者 source /root/fun1.sh
funWithParam 11 22 33 44 55 66 77 88 99 100 101