【问题标题】:Cron jobs output on console控制台上的 Cron 作业输出
【发布时间】:2021-01-24 01:54:31
【问题描述】:

我写了一个shell脚本(myscript.sh):

#!/bin/sh
ls
pwd

我想为每分钟安排一次这项工作,它应该显示在控制台上。为了做到这一点,我已经完成了crontab -e:

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

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

我必须进行哪些更改才能在控制台上打印输出?

【问题讨论】:

    标签: ubuntu cron


    【解决方案1】:

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

    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

    【讨论】:

    • 我们可以每隔一分钟在屏幕上定期打印输出而不是重定向到文件中吗?
    • 所以你想从本质上捕获整个输出,然后突然在你的控制台上打印出来?您是否尝试过不重定向到文件的第二种解决方案?
    • 我按照您提到的相同程序进行操作。但它给出的消息类似于 /bin/sh: /root/crontest/wrapper.sh: Permission denied in /var/mail/root。我不明白为什么要给这个。
    • 多半是因为你没有给 wrapper.sh 赋予执行权限
    • 我现在已经赋予了执行权限并尝试执行 register.sh 它在 /var/mail/root 中显示如下,/root/crontest/wrapper.sh: line 6: /root/ crontest/register.txt:没有这样的文件或目录并显示“ls,pwd”的输出实际上我有一个疑问,我是否必须将 myscript.sh 放在你评论为 # register.sh 的 console.sh 中跨度>
    【解决方案2】:

    我试图实现一个 cron 作业的输出到一个 gnome 终端,并通过它来管理它

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

    我想如果你没有 GUI 而你只有 CLI 你可能会使用

    */1 * * * * /root/myscript.sh > /dev/tty1
    

    实现将 crontab 作业的输出重定向到您的控制台。但首先一定要找到你的终端的名称。如果它是 /dev/tty1 或其他东西。我不确定如何在所有情况下都做到这一点,可能类似于

    env | grep -i tty 
    

    【讨论】:

    • 我寄予厚望,但我在运行 buster lite 的树莓派上尝试了*/1 * * * * date &gt; /dev/tty1,但没有看到任何输出。
    • 首先检查您的活动终端会话名称是什么。也许像 env | grep -i tty
    • 满分。 /dev/pts/0 为 CLI 工作。谢谢
    猜你喜欢
    • 2015-01-26
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    • 2015-01-16
    • 2015-10-09
    • 2013-02-05
    相关资源
    最近更新 更多