ubuntu - 控制台上的 Cron 作业输出

标签 ubuntu cron

我写了一个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/

相关文章:

node.js - 如何通过 cron 作业执行 Node.js 脚本?

linux - 尽管在 sudoers 中拥有完全权限,但没有文件权限

postgresql - 使用日期访问 Postgres 终端历史记录

node.js - Vagrant ssh 提示 'no kex alg' 无法连接虚拟机

docker - 如何在通过 CircleCI 运行的 Ubuntu 中启动 Redis

ruby-on-rails - 使用 每当 gem for Rails 在 cron 作业中重复进程

kubernetes - 这个 cron 作业有什么问题,它没有运行。如何调试它

google-app-engine - 如何在 Google Cloud Platform 上安排 Cron 作业?

java - Spring Cron 表达式 : 10 minutes after every hour

apache - 我的 httpd.conf 是空的