Andy
Andy

Reputation: 407

shell script redirect output

I have a shell script to monitor process due to preventing the process closed. If the process is closed, that script will restart it. BTW, when the system starts, the crontab will run the script automatically. How can I get the output of the process which started by the shell script?

#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
while :
do
if [ -z "$(ps -ef | grep -v grep | grep 225.0.6.4)" ]; then
        date +"%m-%d-%y %T" >> /home/andy/log/stream.log
        echo  "225.0.6.4 - 103 not worked and restart process" >> /home/andy/log/stream.log
         echo "225.0.6.4 - 103 not worked and restart process"

/usr/bin/tzap -a 1 -c /home/andy/channels.conf -o - -r -p "D" | /home/andy/ffmpeg -f mpegts -i pipe:0 -c:v libx264 -preset medium -crf 23 -bufsize 3000K -minrate 1200k -maxrate 1200k -pix_fmt yuv420p -g 50 -s 1024x768 -acodec libmp3lame -b:a 128k -ac 2 -ar 44100 -f mpegts udp://225.0.6.4:50000 &

fi
sleep 1
done

Upvotes: 0

Views: 598

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754880

It looks as though you want the output from the pipeline to go to the log file too. If so, then:

#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

exec >> /home/andy/log/stream.log

while :
do
    if [ -z "$(ps -ef | grep -v grep | grep 225.0.6.4)" ]; then
       date +"%m-%d-%y %T" >> /home/andy/log/stream.log
       echo "225.0.6.4 - 103 not worked and restart process"
       echo "225.0.6.4 - 103 not worked and restart process" >&2

       /usr/bin/tzap -a 1 -c /home/andy/channels.conf -o - -r -p "D" |
       /home/andy/ffmpeg -f mpegts -i pipe:0 -c:v libx264 -preset medium -crf 23 \
           -bufsize 3000K -minrate 1200k -maxrate 1200k -pix_fmt yuv420p -g 50 \
           -s 1024x768 -acodec libmp3lame -b:a 128k -ac 2 -ar 44100 -f mpegts \
           udp://225.0.6.4:50000 &

    fi
    sleep 1
done

The line exec >> /home/andy/log/stream.log ensures that all standard output goes to the log file. I've cheated slightly by arranging things so that the log message that used to go to standard output now goes to standard error instead. If you must have it go to the original standard output, then:

exec 3>&1 >> /home/andy/log/stream.log

…

       echo "225.0.6.4 - 103 not worked and restart process" >&3

This does that job. It actually isn't much harder. The 3>&1 makes file descriptor 3 refer to the same place that standard output refers to (and the rest of the line promptly makes standard output refer to the log file). The >&3 redirects the output to file descriptor 3, which is the same as the original standard output.

Upvotes: 1

Related Questions