Skip to content

Instantly share code, notes, and snippets.

@erincerys
Last active October 6, 2025 12:08
Show Gist options
  • Save erincerys/dcea6cbb46b1b8f6a1ab3634000a5fd7 to your computer and use it in GitHub Desktop.
Save erincerys/dcea6cbb46b1b8f6a1ab3634000a5fd7 to your computer and use it in GitHub Desktop.
Kill processes holding locks on a given file path by progressively issuing higher severity signals for each PID.
#!/bin/bash
# shellcheck disable=SC2086
#
# DESCRIPTION:
# 'safely' kill processes holding file locks for a file path
# useful for managing mountpoints with user session state changes
#
# USAGE:
# $0 <file-path>
#
acquireLocks() {
local -a _LOCKS
mapfile -t _LOCKS < <(
lsof -Fp $1 2>/dev/null |
sed 's/^p//g'
)
if [ ${#_LOCKS[@]} -gt 0 ]; then
echo "${_LOCKS[@]}"
return
else
return 1
fi
}
# Iterate through locking PIDs, sending
# progressively higher severity signals
SIGNALS=(15 1 3 6 9)
for s in "${SIGNALS[@]}"; do
mapfile -t LOCKS < <(acquireLocks $1)
for f in "${LOCKS[@]}"; do
kill -$s $f
done
# Wait ~5s only when locks remain
sleep 0.25
mapfile -t LOCKS < <(acquireLocks $1)
test ${#LOCKS[@]} -gt 0 && \
sleep 4.75
done
echo "${_LOCKS[@]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment