camscape - for excellent IT solutions itkb.ro - IT knowledge base

bash :: functie bash pentru generarea unui sir de caractere random

Cristian
Cristian M.
TitleFunctie bash pentru generarea unui sir de caractere random
Tagsbash, random, sir de caractere
Desc.Functie bash pentru generarea unui sir de caractere random
CodeKBSH0008 v1.0
Date25 septembrie 2012
Functie bash care genereaza un sir random de caractere, de lungimea dorita.

Primeste doi parametri:
- lungimea dorita a sirului de caractere (implicit 32)
- tipul de caractere (0 foloseste numai alfanumerice pentru generare, 1 foloseste alfanumerice si semne)

function GenerateRandomString() {

    # Function to generate a random string
    #
    # Param:
    #   - number of characters, defaults to 32
    #   - 0 if only chars and numbers, 1 if it should include signs
    #
    # Return:
    #   - Generated string
    #
    # Copyright CAMSCAPE SERVICES GPLv2
    # http://www.camscape.ro
    #

    if [ "$2" == "0" ]; then
        CHAR="abcdefghijklmnopqrstuvxywzABCDEFGHIJKLMNOPQRSTUVXYWZ0123456789"
    else
        CHAR="abcdefghijklmnopqrstuvxywzABCDEFGHIJKLMNOPQRSTUVXYWZ0123456789!@#$%^&*(\\)\_\+\-\=\[\]\{\}\;\'\\\:\"\,\.\/\<\>\?\|\`\~"
    fi

    cat /dev/urandom | tr -cd "$CHAR" | head -c ${1:-32}
    echo

}