我写了一个shell脚本( myscript.sh):
#!/bin/sh
ls
pwd
Run Code Online (Sandbox Code Playgroud)
我想每分钟安排一次这项工作,它应该显示在控制台上。为了做到这一点,我已经做了crontab -e:
*/1 * * * * /root/myscript.sh
Run Code Online (Sandbox Code Playgroud)
在这里,它在文件中显示输出,/var/mail/root而不是在控制台上打印。
为了在控制台上打印输出,我必须进行哪些更改?
我能想到的最简单的方法是将输出记录到磁盘,并有一个控制台窗口不断检查日志文件是否已更改并打印更改。
定时任务:
*/1 * * * * /root/myscript.sh | tee -a /path/to/logfile.log
Run Code Online (Sandbox Code Playgroud)
在控制台中:
tail -F /path/to/logfile.log
Run Code Online (Sandbox Code Playgroud)
这样做的问题是您将得到一个不断增长的日志文件,需要定期删除该文件。
为了避免这种情况,你必须做一些更复杂的事情,即确定你想要写入的控制台 pid 并将其存储在预定义的位置。
控制台脚本:
#!/usr/bin/env bash
# register.sh script
# prints parent pid to special file
echo $PPID > /path/to/predfined_location.txt
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
crontab 用法:
*/1 * * * * /root/wrapper_script.sh /root/myscript.sh /path/to/predefined_location.txt
Run Code Online (Sandbox Code Playgroud)
现在您所要做的就是register.sh在您希望程序打印到的控制台中运行。
| 归档时间: |
|
| 查看次数: |
25347 次 |
| 最近记录: |