Last active
November 10, 2024 22:59
-
-
Save book000/28fde8a901258dd04979f3ee4246a765 to your computer and use it in GitHub Desktop.
Bashにおけるロック管理による同時実行の禁止制御
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
cd "$(dirname "$0")" || exit 1 | |
# ロックファイルのパス | |
LOCKFILE="$(realpath "$0").lock" | |
# ファイルディスクリプタ9でロックを取得 (エラーメッセージを無視) | |
exec 9>"$LOCKFILE" 2>/dev/null | |
if [ $? -ne 0 ]; then | |
echo "Failed to open lockfile $LOCKFILE. It seems to be already running." | |
exit 1 | |
fi | |
# flockでロックを試み、失敗したらカスタムメッセージを表示 | |
if ! flock -n 9; then | |
echo "Failed to acquire lockfile $LOCKFILE. It seems to be already running." | |
exit 1 | |
fi | |
trap 'rm -f "$LOCKFILE"' EXIT | |
trap 'exit 130' INT TERM | |
echo "Successfully acquired lock! Start processing." | |
set -e | |
exec 2>&1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment