【发布时间】:2021-01-24 01:54:31
【问题描述】:
我写了一个shell脚本(myscript.sh):
#!/bin/sh
ls
pwd
我想为每分钟安排一次这项工作,它应该显示在控制台上。为了做到这一点,我已经完成了crontab -e:
*/1 * * * * /root/myscript.sh
在这里,它在文件/var/mail/root 中显示输出,而不是在控制台上打印。
我必须进行哪些更改才能在控制台上打印输出?
【问题讨论】:
我写了一个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。
【讨论】:
我试图实现一个 cron 作业的输出到一个 gnome 终端,并通过它来管理它
*/1 * * * * /root/myscript.sh > /dev/pts/0
我想如果你没有 GUI 而你只有 CLI 你可能会使用
*/1 * * * * /root/myscript.sh > /dev/tty1
实现将 crontab 作业的输出重定向到您的控制台。但首先一定要找到你的终端的名称。如果它是 /dev/tty1 或其他东西。我不确定如何在所有情况下都做到这一点,可能类似于
env | grep -i tty
【讨论】:
*/1 * * * * date > /dev/tty1,但没有看到任何输出。