Last Updated: March 11, 2024
·
55.18K
· Lorin Hochstein

Generate UUID at shell prompt

I often need to generate uuids. Here's an alias in my ~/.profile that will generate a uuid, show it on the terminal, and copy it to the OSX clipboard:

alias uuid="python -c 'import sys,uuid; sys.stdout.write(uuid.uuid4().hex)' | pbcopy && pbpaste && echo"

Works like this:

$ uuid
34469137412242129cd908e384717794

Philip Durbin (@philipdurbin) and Matthew Deiters (@mdeiters) both pointed out that I could have used uuigen instead. Here's what the same thing would like using uuidgen.

alias uuid="uuidgen | tr -d - | tr -d '\n' | tr '[:upper:]' '[:lower:]'  | pbcopy && pbpaste && echo"

I don't like how uuidgen generates hyphens and uppercase letters, so I use tr to remove the hyphen and convert to lowercase. I also remove the trailing '\n' that uuidgen adds because I'm typically copy-pasting a uuid into a quoted strong.

4 Responses
Add your response

another nice trick on OSX is the command line utility uuidgen

over 1 year ago ·

@mdeiters Forgot about the existence of uuidgen, I edited the tip.

over 1 year ago ·

@lorin tr lets you specify a set of characters with -d, so this is a bit shorter:

uuidgen | tr -d '\n-' | tr '[:upper:]' '[:lower:]'

over 1 year ago ·

Remove the \n from the argument for -d and the output will be displayed on its own line and not appended to the terminal prompt that's displayed after the operations finish, just as with uuidgen used on its own.

over 1 year ago ·