Created
February 19, 2022 22:52
-
-
Save JackZielke/e00270c83ebac0e702eb00eaf122ac29 to your computer and use it in GitHub Desktop.
Run one copy of this script - oneliner
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/dash | |
# Is this script already running? | |
pidof -x $(basename $0) -o $$ >/dev/null && exit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Summary
I have added code to several scripts that tries to ensure that only 1 copy of the script is running at a time. I usually do this to cron jobs that have an indeterminate run length. The last time I needed to do this I took the time to write generic code that could be pasted into any bash script.
The Code
# only run 1 copy
if [ "$pidof -x -o $$ $(basename $0))" != "" ]; then exit fi
This was later shortened to
pidof -x $(basename $0) -o $$ >/dev/null && exit
The description below was written for the original version but applies to the current version pretty well.
Problems
Each script that contains this code must have a unique name.
This does not detect if the duplicate copy is running as the same user as the script that is checking.
How it works
This piece of code runs two external programs:
pidof (link to killall5)
basename
In Ubuntu, pidof is included with sysvinit-utils and basename is in coreutils.
basename
Let's look at basename first. The man page says:
pidof
Now let's see what we are doing with pidof. Again the man page has some useful information.
-o allows us to omit a PID. By using the $$ variable (mentioned in the section of the bash man page quoted above) the PID of the current script will be used as an argument to -o.
Our final question to pidof looks something like: Are there any scripts, other than myself, running with the same name? pidof returns PIDs separated by spaces. If it returns any output at all then there is already a script running with the same name other than ourselves. In that case the script will exit.
You could have an error displayed on the screen or log an error or something but I think in most cases just halting the execution of the script is enough.
The new version uses the exit status from pidof, and the control operator && used in the command list.