Generating a UUID from the Command Line
There's more than one occasion where I need a random UUID. Usually it's when I'm working with seed data or creating unique IDs for assorted things.
Sometimes the packages I'm using in my project have a command line tool, but more often than not I generally use one of the many website generators out there.
It took me a little while, but I got curious to see if there was a native Mac command. Turns out, there is!
Here, I've written a small function that I've put in my ~/.zhrc
(other folks might use ~/.bashrc
). It generates a new UUID 4 in lowercase, copies it to my clipboard, and outputs it to the console for good measure.
function uuid() {
# Generate a new UUID in lowercase.
local id=$(uuidgen | tr "[:upper:]" "[:lower:]")
# Copy it to the clipboard without a new line.
echo -n $id | pbcopy
# Output it to the console too.
echo $id
}
One ID at a time is okay, but maybe we need a few at once. Here's another function that does the same thing for a given number of times.
function uuids() {
# Loop for the first arg number of times or 3 by default.
for i in {1..${1:-3}}; do uuidgen | tr "[:upper:]" "[:lower:]"; done
}
Calling this uuids
function will output 3 IDs by default, or you can pass it a number like uuids 5
.
There's no explicit upper limit protection here, so using big numbers isn't advised!