Bash: Need help with grep

Hi, I want to write a bash that can turn an application on if it is off or on if it is off. I found a script for LibreELEC, but my OS is OSMC (a Linux distribution, too). I already modiefied lines 5 and 7:

#!/bin/sh
SERVICE='hyperiond'
if ps | grep -v grep | grep $SERVICE > /dev/null
then
sudo systemctl stop hyperion.service 2>/dev/null; sudo /etc/init.d/hyperion stop 2>/dev/null ; sudo /sbin/initctl stop hyperion 2>/dev/null
else
sudo systemctl start hyperion.service 2>/dev/null ; sudo /etc/init.d/hyperion start 2>/dev/null ; sudo /sbin/initctl start hyperion 2>/dev/null
fi

Line 5 and line 7 work when I use them in Putty, so I think line 1 to 3 are the problem. If I run the script it only turnes the application on, but not off. Can you tell me what lines 1 to 3 do so I can fix them? I found a phython script that should work and do the same, just for reference (I want to use bash, as I want to expand the script once it's running).

 import subprocess
pid = subprocess.Popen('pidof hyperiond', shell=True, close_fds=True, stdout=subprocess.PIPE)
try:     
if pid.stdout.readlines():
subprocess.Popen('killall hyperiond', shell=True)
else:
subprocess.Popen('/opt/hyperion/bin/hyperiond /etc/hyperion.config.json </dev/null >/dev/null 2>&1 &', shell=True)
except Exception, e:
pass

Thanks :slight_smile:

Instead of

if ps | grep -v grep | grep $SERVICE > /dev/null

try

if pgrep "$SERVICE" > /dev/null

Stupid question, but why

sudo systemctl stop hyperion.service 2>/dev/null; sudo /etc/init.d/hyperion stop 2>/dev/null ; sudo /sbin/initctl stop hyperion 2>/dev/null

Each of these commands does the same thing. Wouldn't this be better?

if pgrep "$SERVICE" > /dev/null
then
   if [ -x /bin/systemctl ] 
   then sudo systemctl stop hyperion.service 2>/dev/null
   elif [ -x /sbin/initctl ] 
   then sudo /sbin/initctl stop hyperion 2>/dev/null
   else sudo /etc/init.d/hyperion stop 2>/dev/null
   fi
else
   if [ -x /bin/systemctl ] 
   then sudo systemctl start hyperion.service 2>/dev/null
   elif [ -x /sbin/initctl ] 
   then sudo /sbin/initctl start hyperion 2>/dev/null
   else sudo /etc/init.d/hyperion start 2>/dev/null
   fi
fi

Andrew

1 Like

Thanks a lot Andrew, it works perfectly fine :slight_smile: My batch knowledge is very limited, I only watched 3 hours of tutorials on Youtube, so I did not know it does the same. I got the commands from the HyperCon.jar, there you can connect to the Raspberry Pi and start/stop the Ambilight. I just grabbed the command that is used in their program.

The service command is quite omnipresent in Linux (e.g. emulated by systemctl )

PATH=/bin:/usr/bin:/sbin:/usr/sbin
export PATH
SERVICE='hyperiond'
if service "$SERVICE" status >/dev/null 2>&1
then
  service "$SERVICE" stop
else
  service "$SERVICE" start
fi
sleep 1 # wait a sec, in case the start/stop runs in the background
1 Like