bashshellffmpegmpd

mpc current song bash script fail safe


I've got a script that loops:

#!/bin/sh
while [ true ]
do
  mpc current > current_song.txt
  mpc idle player
done

However sometimes it fails to get the song details and creates a blank file. FFMpeg is reading this file and it crashes if its blank. Is there any way to fail safe the script so if the file is blank it adds a certain text?

Would the best way be to create a script that tries to read the file and if it turns out blank to insert some text and then sleep for a period of time or is there a more elegant way to do it?


Solution

  • If the file is truly empty ("ls -l" shows length 0) you can put some text into the file with the following:

    #!/bin/sh
    while true
    do
      mpc current > current_song.txt
      if [ ! -s current_song.txt ]; then
        echo SongNotFound.mp3 > current_song.txt
      fi
      mpc idle player
    done