Trouble with variables - BASH scripting

Hi folks, I’m having trouble with variables in this bash script.

#!/bin/bash
a=$(ls -t *.ts | head -n 1 | awk ‘{print $5}’)
sleep 15s
b=$(ls -t *.ts | head -n 1 | awk ‘{print $5}’)
if [ “$a” -eq “$b” ]; then
/bin/bash ./recordlivestream.sh

I have tested them independently on the command line with echo and they work as intended, producing the expected data. eg.

user@pc:~$ a=$(ls -t *.ts | head -n 1 | awk ‘{print $5}’) && echo $a

However, when run as a script the variables stubbornly remain empty!? I have also tried catonating the output into a file with the same result – the output is empty. I have tried looking round the web and have some inkling it might be something to do with the data being stored as a string instead of a number but that doesn’t quite make sense to me - why outputting to a file would also be blank?

I’m very much a noob at scripting (bash or otherwise), I’m hoping more experienced eyes might be able to point out an obvious mistake.

What I am trying to accomplish
I have a separate script that records a livestream using ffmpeg but sometimes it crashes :frowning: . I want to be able to check that the stream is still being recorded and restart the recording as required. I figured that if I check the file size over a period of time, and see that it hasn’t changed, that would be a simple indication that the stream has failed. The logic is as follows:

  1. Find the most recent transport stream and store it’s file size in a variable.
  2. Wait 10, 20 seconds etc.
  3. Check the filesize again and store in a new variable.
  4. If the values of both variables are identical the stream must have hung/crashed, so restart the recording.

So does anyone know how i can get the variables to store the output from awk successfully? Any input much appreciated!

Change that ls -t into ls -lt and it should work, I think.

3 Likes

Wow that was quick. Yes it works thank you!

So it needed the long list format, it must have worked on the command line because i have an alias set :thinking:

Indeed, that would explain it.

Try enabling tracing next time set -x. It helps a lot when debugging scripts.

2 Likes