0

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.

leetbacoon
  • 1,111
  • 2
  • 9
  • 32
  • One lame idea, but you can add some initial code to your `script.sh` which does `ps -al | grep “script.sh”`. If this returns some content, it would mean the process is running. – Mihir Luthra Jul 18 '19 at 04:26
  • Or just change a shared file. Like whenever your script starts, place a `1` in some shared file and when it ends place `0`. – Mihir Luthra Jul 18 '19 at 04:27
  • @Mihir Good idea, however piping commands like `ps` into grep causes some issues where the grep process itself will appear in the list. Try `ps al | grep asdfsadf` and you'll see it. `pgrep` solves this issue. Additionally I'd like to try to stay away from using files as identifiers in case my script were to crash before it can change the file back, thus making it think it's running when it's not. – leetbacoon Jul 18 '19 at 04:28

0 Answers0