bashscriptingdaemons

Checking if a file exists isn't working in a startup daemon


Okay, so I have a headless Raspberry Pi and I long ago created a daemon to make it play a sound effect when it boots up so I know it's (hopefully) ready for an SSH connection.

#!/bin/sh
### BEGIN INIT INFO
# Provides:
# Required-Start:    $local_fs $remote_fs $syslog
# Required-Stop:     $local_fs $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start daemon at boot time
# Description:       Enable service provided by daemon.
### END INIT INFO

case "$1" in
    start)
      omxplayer /home/pi/Music/boku\ satchii.mp3
    ;;
    stop)
    ;;
    restart)
      $0 start
    ;;
    status)
      echo "Running"
    ;;
    *)
      echo "Usage: $0 {start|stop|restart|status}"
      exit 1
    ;;
esac

exit 0

Works just fine.

Now the issue I'm running into is that the Pi loses its ability to network about once a month (I gave up trying to figure out why) and has to be manually rebooted. In order to deal with this I added a weekly reboot to crontab, but it always wakes me up at midnight every Saturday with "BOKU SATCHII!", which stops being funny about halfway through the first occurrence.

I threw down a quick shell script that uses "touch" to create a file "/etc/quietboot" and then reboot. That works fine. I subbed that in for the reboot in crontab, and then I modified the daemon as follows:

start)
  if [-e /etc/quietboot]; then
    sudo rm /etc/quietboot
  else
    omxplayer /home/pi/Music/boku\ satchii.mp3
  fi
;;

So the idea is that if the file exists then it should be deleted, if it didn't exist then play the sound effect. I've been testing it and it just plays the sound effect every time, and never removes the quietboot file. I tried putting the file in home/pi/ instead, but got the same result.

I'm sure I'm making some elementary error here, but I'm not sure what it is. Can anyone help me out?


Solution

  • With regard to your statement:

    if [-e /etc/quietboot]; then
    

    You need extra spaces in there:

    if [ -e /etc/quietboot ]; then
    #   ^                 ^
    # here!            and here!
    

    What your current statement is doing is trying to run the [-e executable and failing. This failure means that the else block is always run.

    You can actually see this if you try (from the command line):

    pax> if [false] ; then echo it was false ; else echo it was true ; fi
    [false]: command not found
    it was true
    
    pax> if [ false ] ; then echo it was false ; else echo it was true ; fi
    it was false