0

I have a bash as below, it has been been launched with nohup firstly, when I launch the same with nohup again, then 2 process will be running, which is not wanted.

#!/bin/sh
i=0
while true
do
    echo $i
    ((i++))
    sleep 1
done

How can I add logic in script to check previous launched process exist? and if exist then kill it firstly to avoid 2 process running at the same time?

I run ps to list the process info and saw below:

shell          6669   6327 12346608  3948 hrtimer_nanosleep   0 S sleep

I can not just kill shell process since maybe some other shell script is running!

lucky1928
  • 8,708
  • 10
  • 43
  • 92
  • The next step doesn't happen until after `sleep` exits. That's true for _every_ foreground step in a script. And, _being_ a `sleep`, it'll exit itself in a second. – Charles Duffy Feb 06 '23 at 15:43
  • 2
    Anyhow, the better answer is **don't use nohup**. Modern operating systems provide process supervision systems (on Linux, the typical one is systemd; MacOS uses launchd; other operating systems provide their own) that are responsible for making sure you don't have more than one instance of a service at a time (unless you _want_ that, in which case you can use features like instanced services). If you _aren't_ up for modern features, another alternative to ensure there's only one copy of your script at a time is `flock`-style locking. – Charles Duffy Feb 06 '23 at 15:43
  • And once you _are_ using `flock`-style locking, that also gives you the kill feature you're asking for, because you can use tools like `fuser -k` to kill any file with a handle on the lock. – Charles Duffy Feb 06 '23 at 15:46
  • See [BashFAQ/045](http://mywiki.wooledge.org/BashFAQ/045). – tjm3772 Feb 06 '23 at 15:50
  • 1
    Also keep in mind that `#!/bin/sh` is not a bash script, make sure you set an appropriate shebang such as `#!/bin/bash` if you want this to run as a bash script. – tjm3772 Feb 06 '23 at 15:51

0 Answers0