I am trying to validate user input against a regular expression.
vari=A
if [ $vari =~ [A-Z] ] ;
then
echo "hurray"
fi
The output I am getting is swf.sh[3]: =~: unknown test operator.
Can you please let me know the test operator I can use?
It's not built into Bourne shell, you need to use grep:
if echo "$vari" | grep -q '[A-Z]'; then
echo hurray
fi
If you want to match the whole string, remember to use the regex anchors, ^
and $
. Note that the -q
flag makes grep quiet, so its only output is the return value, for match/not match.
POSIX shell doesn't have a regular expression operator (or rather, the POSIX test
command does not). Instead, you use the expr
command to do a (limited) form of regular expression matching.
if expr "$vari" : '[A-Z]' > /dev/null; then
(I say "limited" because it always matches at the beginning of the string, as if the regular expression started with ^
.) The exit status is 0 if a match is made; it also writes the number of characters matched to standard output, hence the redirect to /dev/null
.
If you are actually using bash
, you need to use the [[
command:
if [[ $vari =~ [A-Z] ]]; then
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