I put my trap inside an
if
, run the script, and after that second execution, it warns that lock file is held (ok). But when I kill -9
the running PID, the lockfile is not removed.
When I move trap before the if
(what you can see now commented below):
1. then when I kill -9 PID
, lockfile is deleted (ok)
2. but when I run additional executions the scripts, only first one warns because after this first-additional run, the lockfile is removed by trap on EXIT
!
How to get the trap inside if
to remove the lockfile on kill -9
of the script?
-bash
lockfile=/tmp/localfile
#trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT KILL
if ( set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null;
then
trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT KILL
while true
do
ls -ld ${lockfile}
sleep 1
done
rm -f "$lockfile"
trap - INT TERM EXIT
else
echo "Failed to acquire lockfile: $lockfile."
echo "Held by $(cat $lockfile)"
fi
Asked by DonJ
(371 rep)
Mar 22, 2018, 10:57 AM
Last activity: Aug 24, 2023, 09:09 AM
Last activity: Aug 24, 2023, 09:09 AM