Bash: check if string contains characters in regex pattern

How to check if a variable contains characters (regex) other than 0-9a-zand -in pure bash?

I need a conditional check. If the string contains characters other than the accepted characters, simple exit 1.

+4
source share
3 answers

One way to do this is to use a command grep, for example:

 grep -qv "[^0-9a-z-]" <<< $STRING

Then you request a return value grepwith the following:

if [ ! $? -eq 0 ]; then
    echo "Wrong string"
    exit 1
fi

As @mpapis pointed out, you can simplify the above expression:

grep -qv "[^0-9a-z-]" <<< $STRING || exit 1

You can also use the bash operator =~, for example:

if [[ ! "$STRING" =~ [^0-9a-z-] ]] ; then  
    echo "Valid"; 
else 
    echo "Not valid"; 
fi
+2

case :

case "$string" in
  (+(-[[:alnum:]-])) true ;;
  (*) exit 1 ;;
esac

, , grep - , .

+2

Using the Bash replacement mechanism to check if $ foo $ bar contains

bar='[^0-9a-z-]'
if [ -n "$foo" -a -z "${foo/*$bar*}" ] ; then
  echo exit 1
fi
0
source

All Articles