2012-05-24 108 views
0

我写了一个shell脚本(myscript.sh):Cron作业输出在控制台上

#!/bin/sh 
ls 
pwd 

我想安排这项工作的每一分钟,并应显示在控制台上。为了做到这一点我做了crontab -e

*/1 * * * * /root/myscript.sh 

在这里,它是显示文件/var/mail/root的输出,而不是在控制台上打印。

我必须做什么改变才能在控制台上打印输出?

回答

4

我能想到的最简单的方法是将输出记录到磁盘,并有一个控制台窗口不断检查以查看日志文件是否已被更改并打印更改。

的crontab:

*/1 * * * * /root/myscript.sh | tee -a /path/to/logfile.log 

控制台:

tail -F /path/to/logfile.log 

这里的问题是,你会得到,这将需要定期删除的不断增长的日志文件。

为了避免这种情况,您将不得不做一些更复杂的事情,从而确定您希望写入的控制台pid并将其存储在预定义的位置。

控制台脚本:对于crontab的

#!/usr/bin/env bash 

# register.sh script  
# prints parent pid to special file 

echo $PPID > /path/to/predfined_location.txt 

包装脚本

#!/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程序打印到。

+0

我们能否在屏幕上每分钟后定期打印输出,而不是重定向到文件中? –

+0

所以你想要基本上捕捉整个输出,然后突然打印你的控制台的所有一次吗?你有没有尝试第二个不重定向到文件的解决方案? – Dunes

+0

我遵循了你提到的相同程序。但它给出的信息如 /bin/sh:/root/crontest/wrapper.sh:在/ var/mail/root中,权限被拒绝 。我无法理解它为什么给出这个。 –

1

我试图实现一个cron作业GNOME终端的输出,并以此

*/1 * * * * /root/myscript.sh > /dev/pts/0 

,如果你没有一个GUI,你只需要CLI您可以使用

我想管理它
*/1 * * * * /root/myscript.sh > /dev/tty1 

实现将crontab作业重定向到控制台的输出。