Generate a UUID in Bash

Bash, the widely-used terminal shell and scripting language for Unix-like operating systems (such as Linux or macOS), offers various approaches to generate UUIDs. In this article, we will explore three popular methods that can be utilized for this purpose.

How to Generate a UUID using Bash

Note: To follow this tutorial, you should have a basic understanding of Bash shell scripting and access to a Unix-like operating system (e.g., Linux or macOS) with a terminal emulator.

There are several ways to generate UUIDs in Bash, and we'll cover three popular methods below.

Method 1: Using the uuidgen Command

One of the simplest ways to generate a UUID in Bash is by employing the uuidgen command, which is readily available on most Unix-based systems. Execute the following command in your terminal:

uuidgen

Upon execution, this command will generate a random UUID and display it on the console. If you wish to store the generated UUID in a variable, employ the following syntax:

uuid=$(uuidgen)
echo $uuid

Method 2: Leveraging the /proc/sys/kernel/random/uuid File

In instances where the uuidgen command is unavailable on your system, Linux systems provide an alternative method using the /proc/sys/kernel/random/uuid file. This file yields a random UUID each time its content is accessed. Follow these steps to read the UUID from the file:

uuid=$(cat /proc/sys/kernel/random/uuid)
echo $uuid

Method 3: Generating UUIDs with OpenSSL

Another viable approach to generate a UUID in Bash is by utilizing the OpenSSL command-line tool, which is commonly accessible on Unix-based systems. Employ the following command to generate a UUID using OpenSSL:

uuid=$(openssl rand -hex 16)
echo ${uuid:0:8}-${uuid:8:4}-${uuid:12:4}-${uuid:16:4}-${uuid:20:12}

This command generates a 16-byte random hexadecimal number, which is then formatted according to the standard UUID representation (8-4-4-4-12).

Conclusion

In this comprehensive guide, we have explored three distinct methods for generating UUIDs using Bash shell scripting. Depending on the availability of tools such as uuidgen or OpenSSL on your system, you can choose the method that best suits your needs. UUIDs play a crucial role in various applications, and the ability to effortlessly generate them in Bash can save you valuable time and prevent potential collisions in your projects.