Search code examples
bashautomationsymbolspassword-generator

Generate two random symbols for mysql password in bash


Hi I have a bash script I wrote for my plesk installation.

It triggers when a new subscription is created and does the following:

  • Generates a password in a given format using two random symbols
  • Creates the db in plesk via cli
  • Downloads and unpacks wordpress to the httpdocs dir of that subscirption
  • Configures the wp-config.php for the site
  • Mails me the config details

One problem though is sometimes I generate two symbols that seem to invalidate my password string. I think it's because some symbols need escaping in bash and it's not happening. Is there a way I can randomly grab two symbols from an array of "allowed" symbols?

Here is my genPassword() function

genpasswd() {
local pass=`cat /dev/urandom | tr -cd "[:punct:]" | head -c 2`
echo "$pass"
echo "INFO: genpasswd() ran successfully" >> /usr/run.log
}

Solution

  • Using bash arrays and the "magic" variable RANDOM might help:

    bash$ symbols=(":" "+" ";" ".")
    bash$ echo ${symbols[ RANDOM % ${#symbols[@]} ]}
    ;
    
    bash$ echo ${symbols[ RANDOM % ${#symbols[@]} ]}
    +
    

    If you need to generate a pair (for example):

    bash$ s1=${symbols[ RANDOM % ${#symbols[@]} ]}
    bash$ s2=${symbols[ RANDOM % ${#symbols[@]} ]}
    bash$ echo "${s1}${s2}"
    ;: