Generating Bash Random File Names
Jan 07 2024
In Bash, generating random file names can be useful for uniquely naming files or folders. Here's a guide on how to generate random file names in Bash.
Let's get started
Using date and /dev/urandom
This approach to generating a random file name is by combining the date
command with /dev/urandom
(a special file that provides pseudo-random data).
Here’s an example:
#!/bin/bash
# Generate a random string using date and urandom
random_string=$(date +%s%N | sha256sum | base64 | head -c 12)
# Create a file with the random string in the name (Optional)
random_file="file_$random_string.txt"
touch $random_file
echo "Random file name: $random_file"
In this example,
- The
date +%s%N
command generates a timestamp with nanosecond precision sha256sum | base64
converts it into a base64-encoded string.- The
head -c 12
limits the string length to 12 characters. - Finally, the random string is appended to the file name, and a file with that name is created using touch.
Using /dev/urandom Directly
You can also use /dev/urandom
directly to generate random strings.
Here’s an example:
#!/bin/bash
# Generate a random string using urandom
random_string=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 12)
# Create a file with the random string in the name
random_file="file_$random_string.txt"
touch $random_file
echo "Random file name: $random_file"
In this example,
head /dev/urandom | tr -dc A-Za-z0-9 | head -c 12
extracts random alphanumeric characters,- The resulting string is used to create a file name.
Conclusion
Choose the method that best fits your requirements, and feel free to adjust the length or format of the random string based on your specific needs. Generating random file names can be a handy skill when working with Bash scripts and automation tasks.
If you want to learn more about Bash, then you can check the following articles:
Thank you for reading.