Ensure that a script is executed only once by utilizing a lock mechanism. This can be particularly useful for long-running processes or to guarantee that data is accessed by a single process simultaneously.
#!/usr/bin/env bash
pid_file=~/.MYSCRIPT.pid
if [ -f "${pid_file}" ]; then
if ps -p $(cat ${pid_file}) > /dev/null; then
echo $(date +"%Y-%m-%d %T") "Lock ${pid_file} already exists."
exit 1
else
echo $(date +"%Y-%m-%d %T") "Lock ${pid_file} exists but process " $(cat
${pid_file}) " not found. Removing lock."
rm ${pid_file}
fi
fi
echo $$ >> ${pid_file}
# Do the work
rm ${pid_file}