Using flock to wait for a lock file to be released
I love flock.
I frequently use it to wait something like 10 sec for apt to finish its unattended upgrades and release the apt lock, like this :
(
flock -w 10 9 || exit 1
aptly repo remove $repo $files
) 9>/var/lock/aptlock