我已经用sql语句查询出了一些东西放到文件里面 每五分钟去查一次,如果查出来有内容的话就把这个文件发送到另外一台同网的主机B上;如果查出来内容为空的话就把这个生成的文件删掉,请问如何用shell实现(用sql语句查询数据库生成相应文件这步我已经实现了)。
# Generate results.txt from SQL
# ...
if [ -s results.txt ]; then
# The file is not empty.
# Copy the file to another machine with scp, ftp, ...
scp results.txt username@ip:/path/to/save/results.txt
else
# The file is empty. Remove the file.
rm -f results.txt
fi
这个我做过类似的,你可以用linux的crontab 来做,很简单的
安装
yum -y install crontab
启动crond服务
service crond start
查看状态service crond status
使用crontab -e进行定时任务的编辑
格式: 分 时 日 月 周 [用户] command
这里我写入0 * * * * /root/anaconda3/bin/python3 /root/.py, 表示每天每小时0分时自动执行python3 /root/.py命令。
注意: 设置好运行命令的绝对路径和被执行文件的绝对路径,因为crontab本身不具备平时运行的环境变量。
使用crontab -l查看设置好的定时任务
第一步、编写判断sql文件是否为空的脚本;
#vim check_sql.sh
#!/bin/bash
#script name: check_sql.sh
#将脚本放置到sql文件所在目录
curdir=`cd -P $(dirname $0); pwd`
cd $curdir
if [ -s results.sql ]; then
scp results.sql username@serverB-ip:/dir/results.sql
else
rm -f results.sql
第二步、配置定时任务
#crontab -e
#####5分钟执行一次定时任务,dir为第一步shell脚本存储路径####
*/5 * * * * sh /dir/check_sql.sh &> /tmp/sql_check.log
sql查;
判断文件有无内容;
有,则传输;
无,则删除
写到定时任务,5分钟执行一次即可