2012-05-24 71 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作業重定向到控制檯的輸出。