Home > Blockchain >  bash - read variable from 5 to 20 characteres long, only letters and numbers and _ as character
bash - read variable from 5 to 20 characteres long, only letters and numbers and _ as character

Time:02-26

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 :)

CodePudding user response:

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

CodePudding user response:

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
  •  Tags:  
  • bash
  • Related