A tool such as flock can help manage locks. (It doesmay not work with NFS, depending on whether you believe the documentation or the practice, and probably won'tsimilarly may or may not work on SMB or indeed any other remote filesystem.)
The documentation, man flock, does have several examples of use. Here's one of them tailored to your scenario.
#!/bin/bash # Example of using flock(1) to provide a named exclusive lock # Parse command line options while getopts 'd:' OPT do case "$OPT" in d) lockParam="$OPTARG" ;; *) echo "Usage: ${0##*/} -d <parameter>" >&2; exit 1 esac done shift $(($OPTIND -1)) # Sanitise lock parameter value (do not trust the user) lockName="$(printf "%s\n" "${lockParam^^}" | tr -cd '[:alnum:]\n')" lockFile="/tmp/lock.${##*/}.${lockName:-noname}" echo "Attempting lock with parameter '$lockParam' sanitised to '$lockName'" >&2 ( # Get the lock or report failure. See "man flock" for other options flock -n 9 || exit 9 # This section is managed by the exclusive lock. Your program code # would go here. echo "Achieved exclusive lock on '$lockFile'" >&2 sleep=10 echo "Waiting for $sleep second(s) to simulate activity" >&2 sleep $sleep # Exit status 0=ok, otherwise 1-8 is your choice of error codes echo "Releasing lock" >&2 exit 0 # End of exclusive lock section ) 9>"$lockFile" ss=$? # Report on exit status from actual code if [ $ss -eq 9 ] then echo "Failed to acquire lock" >&2 fi # Exit with meaning exit $ss Make the script executable (if you call it lockeg then chmod a+x lockeg), and run it
./lockeg -d JOHN_DOE