Shell – Check for Process if Same is Running

processscriptingshell-script

Is there a script or a way in linux that when I try to execute a shell script/process, if the same is running, it will prompt that same is running and will exit otherwise it will continue.

Best Answer

You can use this one liner to do what you want:

$ pgrep script.bash && echo "already running" || ( ./script.bash & )

Example

Say I had this script:

$ cat script.bash 
#!/bin/bash

echo "Hello World"
sleep 10

If we use our one liner:

$ pgrep script.bash && echo "already running" || ( ./script.bash & )
Hello World
$

We run it again:

$ pgrep script.bash && echo "already running" || ( ./script.bash & )
10197
already running
$

Waiting 10 seconds and running it again, it again works:

$ pgrep script.bash && echo "already running" || ( ./script.bash & )
Hello World
$
Related Question