I have written a shell script (myscript.sh):
#!/bin/sh
ls
pwd
I want to schedule this job for every minute and it should display on the console. In order to do that I have done crontab -e:
*/1 * * * * /root/myscript.sh
Here, it's display the output in the file /var/mail/root rather than printing on the console.
What changes I have to make inorder to print the output on console?
The easiest way I can think of is to log the output to disk and have a console window constantly checking to see if the logfile has been altered and printing the changes.
crontab:
*/1 * * * * /root/myscript.sh | tee -a /path/to/logfile.log
in console:
tail -F /path/to/logfile.log
The problem with this is that you will get an ever growing log file which will need to be periodically deleted.
To avoid this you would have to do something more complicated whereby you identify the console pid that you wish to write to and store this in a predefined place.
console script:
#!/usr/bin/env bash
# register.sh script
# prints parent pid to special file
echo $PPID > /path/to/predfined_location.txt
wrapper script for 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 usage:
*/1 * * * * /root/wrapper_script.sh /root/myscript.sh /path/to/predefined_location.txt
Now all you have to do is run register.sh in the console you want the program to print to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With