我写了一个shell脚本(myscript.sh
):
#!/bin/sh
ls
pwd
我想每分钟安排一次这项工作,它应该显示在控制台上。为了做到这一点,我做了
crontab -e
:*/1 * * * * /root/myscript.sh
在这里,它在文件
/var/mail/root
中显示输出。而不是在控制台上打印。为了在控制台上打印输出,我必须进行哪些更改?
最佳答案
我能想到的最简单的方法是将输出记录到磁盘并有一个控制台窗口不断检查日志文件是否已更改并打印更改。
crontab:
*/1 * * * * /root/myscript.sh | tee -a /path/to/logfile.log
在控制台中:
tail -F /path/to/logfile.log
这样做的问题是您将获得一个不断增长的日志文件,需要定期删除该文件。
为避免这种情况,您必须做一些更复杂的事情,通过识别您希望写入的控制台 pid 并将其存储在预定义的位置。
控制台脚本:
#!/usr/bin/env bash
# register.sh script
# prints parent pid to special file
echo $PPID > /path/to/predfined_location.txt
crontab 的包装脚本
#!/usr/bin/env bash
cmd=$1
remote_pid_location=$2
# Read the contents of the file into $remote_pid.
# Hopefully the contents will be the pid of the process that wants the output
# of the command to be run.
read remote_pid < $remote_pid_location
# if the process still exists and has an open stdin file descriptor
if stat /proc/$remote_pid/fd/0 &>/dev/null
then
# then run the command echoing it's output to stdout and to the
# stdin of the remote process
$cmd | tee /proc/$remote_pid/fd/0
else
# otherwise just run the command as normal
$cmd
fi
crontab 用法:
*/1 * * * * /root/wrapper_script.sh /root/myscript.sh /path/to/predefined_location.txt
现在你所要做的就是运行
register.sh
在您希望程序打印到的控制台中。
关于ubuntu - 控制台上的 Cron 作业输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10732864/