Last active
August 6, 2021 21:27
-
-
Save bkw777/aabe19cb781f54872251d9b443b9448a to your computer and use it in GitHub Desktop.
Example to create an exclusive temp/working dir in bash. Based on the atomicity of mkdir.
This file contains 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 | |
# create an exclusive temp dir | |
# allow bash-isms | |
# b.kenyon.w@gmail.com | |
# If you don't need to retain the temp files after execution, and you reliably | |
# clean up on exit with a trap, and you only need to worry about concurrent | |
# instances, then you can just use $$ cheaper instead of this "until mkdir" loop. | |
# Comment this out to retain the temp files after execution (logging, debugging) | |
trap '[[ -d "$x" ]] && rm -rf "$x"' EXIT | |
# This allows unlimited calls per second, safely with no collsions. | |
# No 2 instances will ever produce the same temp name no matter | |
# how many instances all try simultaneously. | |
_mktmpd () { | |
MKTMPD="${1:-$MKTMPD}" | |
local b="${MKTMPD:-/tmp/${0//\//_}}" ;local p="${b%/*}" | |
[[ -d "$p" ]] || { mkdir -p "$p" ;[[ -d "$p" ]] || exit 1 ; } | |
n=0 MKTMPD="${b}_00000000" | |
until mkdir "$MKTMPD" ;do printf -v MKTMPD '%s_%08d' "$b" $((++n)) ;done | |
} | |
# Optionally specify a base path in MKTMPD, or as an argument. | |
# This example creates a base path of /tmp/${APP_NAME}/YYYY/MM/DD/HH/MMSS | |
# which facilitates retaining the work files as a form of logging. | |
# Final temp dir name will be ex: "/tmp/foo/2021/08/13/15/4403_00000001/" | |
APP_NAME=foo | |
printf -v MKTMPD '/tmp/%s/%(%Y/%m/%d/%H)T' "${APP_NAME}" -1 | |
_mktmpd | |
# Dir is created and the name of the created dir is in $MKTMPD | |
echo "Created \"${MKTMPD}\"" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment