'bash - read variable from 5 to 20 characteres long, only letters and numbers and _ as character
need your help in coding, I can do this using if / else and while but I like to see if there is a way to do it in one or less commands as possible (I like use less lines as possible and more complex commands :D just to learn new things)
I have this command that works to read input having only letters, numbers and _
while [[ "$inp" =~ [^a-zA-Z0-9] || -z "$inp" ]]; do
read -r -p "Please enter name and hit ENTER:" inp;
done
is there a way to add to same command to also check if variable is more than 5 and less than 20 characters?
and going even more if possible, we need to know that starts only with following patterns: p_ d_ s_
thanks :)
Solution 1:[1]
Use ${#inp} to get the length of $inp, you can then compare that with 5 and 20.
To check the first character, use a regular expression that matches the full pattern you want to allow, including the prefix pattern. Then use ! to invert the test in your while condition.
while [[ ${#inp} -lt 5 || ${#inp} -gt 20 || !( $inp =~ ^[pds][a-zA-Z0-9]*$ ) ]]; do
read -r -p "Please enter name and hit ENTER:" inp;
done
Solution 2:[2]
Use a fancier regex, and the until looping construct:
until [[ "$inp" =~ ^[pds]_[[:alnum:]_]{3,18}$ ]]; do
read -r -p "Please enter name and hit ENTER:" inp;
done
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Barmar |
| Solution 2 | glenn jackman |
