In this guide, we will create a bash command that generates random file names within a folder. Although generating random strings, we will encode a random number generated using the $RANDOM variable with base64.
Generate Random Names For Text Files Using Bash Command
Before proceeding with the code snippet, let's examine each bash command that will be utilized to create random file names.
- for file in path/to/folder => For iterating in a folder
- if-fi => For checking a file's extension
- mv => For changing a file's name
for file in /Users/john/Desktop/bash/*
do
if [ ${file##*.} = 'txt' ];
then
RANDOM_HASH=`echo $RANDOM | base64`
mv "$file" "/Users/john/Desktop/bash/$RANDOM_HASH.txt"
fi
done
In short, this command will iterate over files given path with a for loop and check if current file's extension is txt, if so, it will generate a random string and change file names in current folder.
Make sure you give absolute path for folder by obtaining with the pwd command in your bash before running the bash file, because you don't want to harm your files. In addition to this you can configure the command above by changing the required extension or random string generation method.
Conclusion
In this article, we have created a bash command using a for loop and if-else conditionals to generate random file names in a directory. If you run the command above in a directory, it will be rename all files with random string.
Thank you for reading.