In Java i can create a new random UUID with

UUID uuid = UUID.randomUUID();

I now need to do the same within a bash script. Is there a command or library I could use?

link|improve this question

67% accept rate
feedback

4 Answers

up vote 13 down vote accepted

See the uuidgen program which is part of the e2fsprogs package.

link|improve this answer
3  
hey, no fair! my e2fsprogs didn't come with that! i want one, where do i get it? (update: ahhh... debian sticks it in the uuid-runtime package for no apparent reason... +1 to you) – quack quixote Jan 16 '10 at 14:05
feedback

Perl provides a UUID library based on the e2fsprogs package. On my Debian system it's the libuuid-perl package. Here's an example one-liner; see man uuid for more:

$ perl -e 'use UUID;  UUID::generate($uuid);  UUID::unparse($uuid, $string);  print "my new UUID is $string \n";'
my new UUID is 3079e9ce-41d4-4cf3-9f90-d12f8bb752e4

This would be trivial to add to a shellscript with backticks or $() notation:

#!/bin/bash
# ...do some stuff
$myvar = $(perl -e 'use UUID;  UUID::generate($uuid);  UUID::unparse($uuid, $string);  print "$string";')
# ...do some more stuff
link|improve this answer
+1 - Help me a lot! – Castanho Feb 16 '11 at 13:29
feedback

Just so python doesn't feel left out:

python  -c 'import uuid; print uuid.uuid1()'
2d96768e-02b3-11df-bec2-001e68b9d147

Son in the shell:

myvar=$(python  -c 'import uuid; print uuid.uuid1()')

See the Python Documentation for the kinds of UUIDS that can be generated.

link|improve this answer
feedback

Just for the sake of completeness... There's also a UUID generator installed with the dbus package on Debian. I missed it looking around earlier. It's probably the same algorithm as the e2fsprogs package, but it doesn't add the dashes, so it might be a little cleaner for you:

$ uuidgen
387ee6b9-520d-4c51-a9e4-6eb2ef15887d

$ dbus-uuidgen
d17b671f98fced5649a856a54b51c9e6

Grawity adds a safety tip: "DBus UUIDs are not related to or compatible with RFC 4122. Besides, dbus-uuidgen always uses the Unix timestamp as the last 4 bytes. So they might be unsuitable for some uses." (Thanks, Grawity, I should've spotted that in the manpage.)

link|improve this answer
1  
DBus UUIDs are not related to or compatible with RFC 4122. Besides, dbus-uuidgen always uses the Unix timestamp as the last 4 bytes. So they might be unsuitable for some uses. – grawity Jan 16 '10 at 15:08
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.