Generate random shell passwords with one special character

I have the following code:

</dev/urandom tr -dc 'A-Za-z0-9@#$%&_+=' | head -c 16

      

which randomly generates passwords.

I want two changes:

  • It should only contain one special character as above
  • He must choose an arbitrary length

I tried with length = $(($RANDOM%8+9))

then putting the length as

</dev/urandom tr -dc 'A-Za-z0-9@#$%&_+=' | head -c$length

      

but did not get a positive result.

0


source to share


1 answer


#! /bin/bash
chars='@#$%&_+='
{ </dev/urandom LC_ALL=C grep -ao '[A-Za-z0-9]' \
        | head -n$((RANDOM % 8 + 9))
    echo ${chars:$((RANDOM % ${#chars})):1}   # Random special char.
} \
    | shuf \
    | tr -d '\n'

      



  • LC_ALL=C

    prevents characters such as ř.
  • grep -o

    only outputs the matching substring, i.e. one character.
  • shuf

    moves lines. I originally used sort -R

    but it kept the same characters ( ff1@22MvbcAA

    ).
+3


source







All Articles