Skip to content

Instantly share code, notes, and snippets.

@bertvv
Last active December 17, 2015 04:58
Show Gist options
  • Save bertvv/5553960 to your computer and use it in GitHub Desktop.
Save bertvv/5553960 to your computer and use it in GitHub Desktop.
Generate a file name for a new file, based on the specified prefix and suffix. Uniqueness is guaranteed by a sequence number. E.g. "newfile test- .txt" will return a file name in the form test-NNN.txt where NNN is the first number (001, 002, etc.) that results in a file name that doesn't exist yet.
# Return a file name consisting of the specified prefix, number, and suffix
# 3 arguments:
# $1 - prefix
# $2 - an integer, which will be padded with zeroes to length 3
# $3 - suffix
# e.g. "mkfile test- 2 .txt" will return "test-002.txt"
mkfile ()
{
echo "${1}$(printf '%03d' ${2})${3}"
}
# Generate a file name for a new file, based on the specified prefix and
# suffix. Uniqueness is guaranteed by a sequence number.
# E.g. "newfile test- .txt" will return a file name in the form
# test-NNN.txt where NNN is the first number (001, 002, etc.) that results in
# a file name that doesn't exist yet.
#
# 2 arguments:
# $1 - prefix
# $2 - suffix
# E.g. calling "newfile test- .txt" will return, consecutively:
# test-001.txt, test-002.txt, test-003.txt, etc.
newfile ()
{
i=1
while [ -f "$(mkfile $1 $i $2)" ]; do
((i++))
done
mkfile $1 $i $2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment