I'm working on a problem in unix bash where it wants me to get an input from the user and then find if the input is valid (i.e. contains only A-Z a-z and the _ underscore character) and reject anything with a character other than those. For example Space_oddity would be valid while Space_oddity132 would be invalid. I'm having trouble figuring out what the syntax of the grep command would be
if $1 | grep '[A-Za-z_]'
echo "name is valid"
else
echo "name is not valid"
fi
I think I'm supposed to be using {m,} in the grep command but I'm not able to get the correct syntax despite looking at the list of regex commands. Can anybody help me get the correct syntax or post something that is more helpful in understanding the syntax then what I have found so far?
The case
statement can accomplish this task and it is POSIX and consequently has the advantage of being portable:
#!/bin/sh
case "$1" in
*[^[:alpha:]_]* )
echo "name is not valid" ;;
*)
echo "name is valid" ;;
esac
This works because, if $1
contains any unallowed character, that character will match [^[:alpha:]_]
and the not valid
message will be displayed.
Using similar logic but using bash's [[...]]
test command:
if [[ $1 = *[^[:alpha:]_]* ]]
then
echo "name is not valid"
else
echo "name is valid"
fi
Alternatively, as suggested by Benjamin W, we can do a substitution to remove all valid characters and then test if the resulting string is empty or not:
if [[ ${1//[[:alpha:]_]} ]]
then
echo "Name is not valid"
else
echo "Name is valid"
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With