I have a shell script with methods:
start(){
echo "Hello world"
}
stop(){
ps -ef|grep script.sh|grep -v grep|xargs kill
}
while [ "$1" != "" ]; do
case "$1" in
        start)
            start
            ;;
        stop)
            stop
            ;;
        *)
            echo $"Usage: $0 {start|stop}"
            exit 1
        esac
   shift
done
I am running this script using this command: ./script.sh start to call the start method.Now, I want to check if this process is already running and exit if it is already running. I have tried some solutions online but nothing worked. Someone please help.
The solutions I have tried were:
if [ -f /var/tmp/script.lock ]; then
  echo "Already running. Exiting."
  exit 1
else
  touch /var/tmp/script.lock
fi
<main script code>
#some code
rm /var/tmp/script.lock
The other one is:
PID=$(ps -ef | grep script.sh|grep -v grep)
   if [ -z $PID ]; then
       echo "Process already running"
       exit   
fi
These solutions doesn't work and exit even when the process is just started.
 
     
    