Generate random passwords in shell with one special character

一个人想着一个人 提交于 2019-12-08 13:25:31

问题


I have the following code:

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

which is randomly generating passwords perfectly.

I want two changes:

  1. It should only contain one special character listed above
  2. It should choose a random length

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

then putting length as

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

but got no positive result.


回答1:


#! /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 like ř from appearing.
  • grep -o outputs just the matching substring, i.e. a single character.
  • shuf shuffles the lines. I originally used sort -R, but it kept the same characters together (ff1@22MvbcAA).


来源:https://stackoverflow.com/questions/30947873/generate-random-passwords-in-shell-with-one-special-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!