Bash while true loop with dynamic execution criteria (variable)
Good day to all, thanks to all supporting stackoverflow, learned a lot here. Upfront, I am a hobbist learning day by day.
I have bash script which works so far one time. Let me explain in short what it does.
I am logging my "application" into tmp file jctl. This application logs changes within a system if a URL request is changing by user action and adding it into jctl as long log entry. Then with a combination of grep/tail I finally filter the usable URL which is my variable "var0". Means "var0" is changing from time to time. Three conditions are possible
- var0 URL is equal - do nothing
- var0 URL has changed - kill running ffmpeg and restart ffmpeg with new URL from var0
- var0 is empty - kill running ffmpeg and wait for new URL from var0
The while true loop generating var0 is working, the part of handover to ffmpeg , start/stop ffmpeg does work one time, when I start the script. When var0 changes or is empty the URL started with script first time is executed.
Expected behavior is: The while loop runs inifinte, updates variable var0 based on the logs in jctl file, and start/stops ffmpeg according the var0 criteria described above.
I hope anyone can help or give the right hint. Thanks in advance.
What it does: It fetches on demand a HLSv5 manifest with separate Video and Audio m3u8 and ffmpeg muxes them to one mpgets stream.
My scrip开发者_StackOverflow中文版t so far:
#!/bin/sh
journalctl -fu application -o cat > /tmp/jctl &
while true
do
cat /tmp/jctl | grep "playing" | tail -n1 | tee /tmp/all
grep -Eo "(prox/http|prox/https)%3a//\[a-zA-Z0-9./?=\_%:-\]\*(:)" /tmp/all |
tail -n1 | sed 's,:,,g' | sed 's,prox/https%3a,https:,g' | tee /tmp/var0
var0=$(sed -n "1p" /tmp/var0)
if [ ! -z "$var0" ] # URL not empty
then
curl -L $var0 | tee /tmp/tmp
var1=$(sed -n '/RESOLUTION=1/{n;p}' /tmp/tmp | sed -n "1p")
var2=$(sed '/DEFAULT=YES[^[]*URI="/!d;s//&\n/;s/.*\n//;:a;/"/bb;$!{n;ba};:b;s//\n&/;P;D' /tmp/tmp | sed -n "1p")
`ffmpeg -re -rtbufsize 8M -i $var1 -i $var2 -c copy -f mpegts udp://227.0.0.1:1234?pkt_size=1316 &`
fi
done
To be able to kill ffmpeg command you have to get it pid, grep it or better store it in special var at the moment of running ffmpeg in bg, like this:
ffmpeg -re ... 1316 & ffmpeg_pid=$!
$ffmpeg_pid
var will store your ffmpeg command's pid.
kill $ffmpeg_pid
And to check that url changed you have to store previous value somewhere, so when you get $var0
store it in $old_url
var for example and than check:
[[ $var0 != $old_url ]] && echo 'url changed'
精彩评论