Skip to main content

Shell function to generate a random string of the specified length in Shell.

#!/bin/sh

random_str_of_length()
{
    if [ -z "$1" ]; then
        echo 'Usage: random_str_of_length <length>'
        echo 'generate a random string of the specified length'
    else
        # Note: "LC_ALL=C" fixes "tr: Illegal byte sequence" error on macOS. Environment LC_ALL was "en_US.UTF-8".
        head /dev/urandom | LC_ALL=C tr -dc A-Za-z0-9 | cut -c1-"${1}"
    fi
}