Bash - 脚本为 运行 时锁定目录以便删除

Bash - Lock directory for deletion while script is running

我想在 Bash 脚本处于 运行 时锁定目录,并确保在脚本终止时它不再被锁定。

我的脚本创建了一个目录,我想尝试删除它,如果我无法删除它,则说明它已被锁定。如果它没有被锁定,它应该创建目录。

rm "$dir_path" > /dev/null 2>&1

if [ -d "$dir_path" ]; then
   exit 0
fi

cp -r "$template_dir" "$dir_path"

# Lock directory
#LOCK "$dir_path"
# flock --exclusive --nonblock "$app_apex_path" # flock: bad file descriptor


# When script ends the lock is automatically removed without need to do any cleanup
# this is necessary because if for example in case of power failure the dir would still
# be locked on next boot.

我已经研究过 flock 但它似乎不是这样工作的。

这是一个建议锁定的示例,只要所有参与的脚本都遵循相同的协议,它就可以正常工作。

set -e

if ! mkdir '/tmp/my-magic-lock'; then
  exit 1  # Report an error, maybe?
fi
trap "rmdir '/tmp/my-magic-lock'" EXIT

# We hold the advisory lock now.
rm -Rf "$dir_path"
cp -a "$template_dir" "$dir_path"

附带说明一下,如果我要解决这种情况,我会简单地制作 $template_dir$dir_path Btrfs 子卷并使用快照而不是副本:

set -e
btrfs subvolume delete "$dir_path"
btrfs subvolume snapshot "$template_dir" "$dir_path"

这^^^更高效,“原子”(以许多有益的方式),写时复制并且对同一类型的多个并发替换尝试具有弹性,一旦全部产生正确的状态尝试完成。