I am writing a password check script and I would like to be able to check if password includes a string of 3 or more of the same characters (aaa, babbb, asj111) all would be a "bad password". I have tried
grep -E '(.)\1{2,}' $password
but I want this in an if statement to then do something if I find more than 3 characters. All help is appreciated!
Asked
Active
Viewed 257 times
0

Jade Fisher
- 143
- 10
-
Usually passwords are stored in hashed form. Why do you think the hash will be "better" if you do not have same characters? – Romeo Ninov Sep 12 '18 at 16:08
-
Possible duplicate of [Regular expression to match any character being repeated more than 10 times](https://stackoverflow.com/questions/1660694/regular-expression-to-match-any-character-being-repeated-more-than-10-times) – Alex M Sep 12 '18 at 16:09
-
@AlexM it's not a duplicate; the question here is about how to combine `grep` and an `if` statement, not about the regex (the OP got that point right). – gniourf_gniourf Sep 12 '18 at 16:10
-
@RomeoNinov yes this is a simple project I am doing to become familiar with shell scripting and learning the basics for it and understanding how it works – Jade Fisher Sep 12 '18 at 16:11
-
1@JadeFisher, OK. But when write scripts always have security in mind – Romeo Ninov Sep 12 '18 at 16:12
-
1`3ksad9jdsaaa9324jk` is probably a much better password than `aabbcc`. Encourage your users to use longer passwords instead of nitpicking about arbitrary restrictions on shorter ones. – chepner Sep 12 '18 at 18:58
-
@chepner I have no users this is for me to understand shell coding... – Jade Fisher Sep 13 '18 at 14:09
2 Answers
3
Use the return code of grep
:
if grep -q '\(.\)\1\1' <<< "$password"; then
echo "Bad password!"
# Do something, like exit 1
fi
The -q
option is to keep grep
quiet. I didn't use the -E
(extended) option, use it if you want.

gniourf_gniourf
- 44,650
- 9
- 93
- 104
-
Would you be able to adapt this to make it any 3 lowercase letters or any 3 uppercase letters? – Jade Fisher Sep 12 '18 at 16:10
-
@JadeFisher: you mean three consecutive lowercase or three consecutive uppercase? Like `thisIsBad` and `THISiSbAd` but `ThIsISgoOd`? – gniourf_gniourf Sep 12 '18 at 16:12
-
2@JadeFisher You could use `grep -q '\([[:lower:]]\{3\}\|[[:upper:]]\{3\}\)'` – gniourf_gniourf Sep 12 '18 at 16:15
1
Put your pattern in a variable. It matches any character, then the same character twice again (so three times in total).
pattern='(.)\1{2}'
Then test it with the bash regex comparison operator =~
[[ $password =~ $pattern ]] && echo "bad password"

Alex M
- 885
- 9
- 12