1
# Check if VPNC is already running, otherwise start it
if ( ps -ef | grep -v grep | grep -v vpnc_ondemand | grep -v less | grep vpnc > /dev/null ) ; then
    echo "Shell script is already running then dont run this script and terminate the script".

exit                
else 

echo "run the other part of script "

I want that if this process is already running then whole script just get terminated itself, and if doesn't run further part of script.

Or this code which I have already written will execute it what am I looking for

3
  • You can simplify that whole sequence of greps using pgrep.
    – muru
    Commented Jun 17, 2014 at 8:05
  • How can i use pgrep in my script
    – kunal
    Commented Jun 17, 2014 at 8:38
  • 2
    if pgrep 'vpnc$' > /dev/null; then echo "That message"; exit 1; fi. See pgrep(1) for more options. In general, pgrep is a much better option compared to using ps and grep. You don't have to filter out the command doing the search, for one.
    – muru
    Commented Jun 17, 2014 at 8:43

2 Answers 2

2

If you need this sort of supervisory management, I'd look to Upstart. Create a new file by running sudoedit /etc/init/vpnc.conf and copy in something like the following:

start on (started networking)
respawn
exec /usr/sbin/vpnc --no-detach

And then just sudo start vpnc to start it up the first time (and it'll auto-start after that). Upstart will track the process by its PID. No scripthackery required.

0

Using the suggestion of @muru here is a bash script that do what you want:

#!/usr/bin/env bash

process='vpnc$'

if pgrep $process > /dev/null; then # Here we are using the fact that if pgrep returns 0, the process is running
    echo "Shell script is already running then dont run this script and terminate the script".
    exit 1 # A number different of zero is good to point out that something went wrong
else
    echo "run the other part of script "
fi

But the answer from @Oli is better suited for what you question looks like it is intented (program management on a server).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .