I have a bash script that performs a list of commands that modify a file on the filesystem. I want to have a background process run while these commands run so that my bash script cannot be invoked while another instance is already running.
Almost something like the following:
#!/bin/bash
if pgrep mystery_background_cmd; then
echo 'The file is being modified right now. Exiting.'
fi
<script commands here>
bg_pid="$( mystery_background_cmd & echo "${!}" )"
<do other commands here>
kill "${bg_pid}"
So, in practice:
$ ./script.sh &
Modifying files...
$ ./script.sh &
The file is being modified right now. Exiting.
Or, better yet, something like:
$ ./script.sh &
Modifying files... # 1st instance
$ ./script.sh &
The file is being modified right now. Seconds until re-check: {5..1} # 2nd instance
The file is being modified right now. Seconds until re-check: {5..1} # 2nd instance
Finished modifying! # 1st instance
Modifying files... # 2nd instance
I am using bash 3.2.57(1)-release and macOS High Sierra 10.13.6.