0

So I'm trying to check for the output of a command, but I also want to be able display the output directly in the terminal.

#!/bin/bash
while :
do
OUT=$(streamlink -o "$NAME" "$STREAM" best)
echo "$OUT"
if [[ $OUT == *"No playable streams"* ]]; then
  echo "Delaying!"
  sleep 15s
fi
done

This is what I tried to do.

The code checks if the output of a command contains that error substring, if so it'd add a delay. It works well on that part.

But it doesn't work well when the command is actually successfully downloading a file as it won't perform that echo until it is finished with the download (which would take hours). So until then I have no way of personally checking the output of the command

Plus the output of this particular command displays and updates the speed and filesize in real-time, something echo wouldn't be able to replicate.

So is there a way to be able to display the output of a command in real-time, while also command substituting them in order to check the output for substrings after the command is finished?

doko
  • 15
  • 4

1 Answers1

0

Use a temporary file:

TEMP=$(mktemp) || exit 1

while true
do
    streamlink -o "$NAME" "$STREAM" best |& tee "$TEMP"
    OUT=$( cat "$TEMP" )
    #echo "$OUT" # not longer needed
    if [[ $OUT == *"No playable streams"* ]]; then
        echo "Delaying!"
        sleep 15s
    fi
done

# not really needed here because of endless loop
rm -f "$TEMP"
Wiimm
  • 2,971
  • 1
  • 15
  • 25
  • The output says `[cli][info]: command not found` for the line `$OUT=$( cat "$TEMP" )` Do you have any idea why? – doko May 30 '19 at 10:28
  • Ok, I'm making some quick experiments. `TEMP=$(mktemp); streamlink "$STREAM" |& tee "$TEMP"; cat "$TEMP"` doesn't output any errors, but `TEMP=$(mktemp); streamlink "$STREAM" |& tee "$TEMP"; $OUT=$( cat "$TEMP" ); echo $OUT` outputs =: command not found in the end – doko May 30 '19 at 11:05
  • Goddamnit I'm an idiot, I figured it out, it's supposed to be OUT=$( cat "$TEMP" ) without the "$" – doko May 30 '19 at 11:16
  • Ok, one more issue: the command doesn't seem to be able to display the real-time progress (download speed, filesize, etc). Is there a way to fix this? – doko May 30 '19 at 11:39
  • Some tools like `grep` use block buffering instead of line buffering for output, if stdout is not connected to a terminal. `grep --line-buffered` fix it. I don't know if `streamlink` does the same and has such option too. – Wiimm May 30 '19 at 11:46
  • Streamlink doesn't seem to have an option like that – doko May 30 '19 at 11:53
  • Addition: You can prove the behavior (block or line buffering) with: `COMMAND |& cat - ` or here with `streamlink -o "$NAME" "$STREAM" best |& cat -` – Wiimm May 30 '19 at 12:35
  • Here's another way to "unbuffer" ... https://stackoverflow.com/a/7162169/620097 . Please fix the TYPO in your answer! ... Then I will up-vote ;-) . Good luck to all. – shellter May 30 '19 at 13:13