On Linux you can use the flock
utility from util-linux:
if ! ( flock -n 42 || exit 1
# Things to do in the single instance
echo "Processing..."
sleep 60
echo "Done"
exit 0
) 42> /var/tmp/mylockfile # any unique filename
then
# Things to do when the script is in use
echo "Sorry, the service is in use."
fi
Just make sure that the subshell in () ends with success (like with exit 0
here), otherwise the then-clause kicks in after your process is finished.