BASH – Generate a Random String
In a recent project, I needed a function that would generate a random string for me. In my case, I was creating a random file name to store some data, but there are other uses as well, so I am posting the BASH code here in the hope that it will help others out there on the net writing BASH scripts and need a good random string function:
#!/bin/bash
function randomString {
# if a param was passed, it's the length of the string we want
if [[ -n $1 ]]; then
local myStrLength=$1;
else
# otherwise set to default
local myStrLength=16;
fi
# create character set, update this as needed
charSet="abcdefghijklmonpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_^!"
myRandomString="";
for i in `seq 1 $myStrLength`; do
char=${charSet:$RANDOM % ${#charSet}:1}
myRandomString+=$char
done
}
randomString $1;
echo $myRandomString;
Save this to a script file (I called mine rand.sh) using the command-line ‘nano’ editor:
me@home:~ $ nano rand.sh
Now mark it as an executable script:
me@home:~ $ chmod +x rand.sh
And now you should be able to run it and pass it whatever you want as the length of your string:
me@home:~ $ ./rand.sh
Bo82z3duWs8yQ0^6
me@home:~ $ ./rand.sh 32
!pP2XWleIwhm7QosN8m5u4wxmXS!eykn
me@home:~ $ ./rand.sh 64
TYv4CDwimTzMdDkQ7FhmXMs7XbHNoF9eVhxN2_n9!1e0wbWaMzDAGs!RuPbPjlWT
me@home:~ $ ./rand.sh 256
svfUuvyxMt1ZBkNmTNnWR!HRlrj-d7YUDluxUMbD^qCkdZ2whC58dGXKv3!9dWIUE6a0WuvGy3nWXmizzW_-5TVWOjotIQbmB7Uf2p5f^HMh49gLTeCBHTGYnU8XJQ8XetFcohKw-_eGfBuZTHGncuZNn-yd8TBH9F49fCbQH!Vw^r5XrRuCl1-X15WXubLy!ojVLNUxzE^lXICzQSF22Ci1WGBUxzAwONvKBqFe^m3_3ZSjFXZbxizxSzY6M6w^
Hope this helps someone!