How do I check if a variable contains characters (regex) other than 0-9a-z
and -
in pure bash?
I need a conditional check. If the string contains characters other than the accepted characters above simply exit 1
.
How do I check if a variable contains characters (regex) other than 0-9a-z
and -
in pure bash?
I need a conditional check. If the string contains characters other than the accepted characters above simply exit 1
.
One way of doing it is using the grep
command, like this:
grep -qv "[^0-9a-z-]" <<< $STRING
Then you ask for the grep
returned value with the following:
if [ ! $? -eq 0 ]; then
echo "Wrong string"
exit 1
fi
As @mpapis pointed out, you can simplify the above expression it to:
grep -qv "[^0-9a-z-]" <<< $STRING || exit 1
Also you can use the bash =~
operator, like this:
if [[ ! "$STRING" =~ [^0-9a-z-] ]] ; then
echo "Valid";
else
echo "Not valid";
fi
case
has support for matching:
case "$string" in
(+(-[[:alnum:]-])) true ;;
(*) exit 1 ;;
esac
the format is not pure regexp, but it works faster then separate process with grep
- which is important if you would have multiple checks.
Using Bash's substitution engine to test if $foo contains $bar
bar='[^0-9a-z-]'
if [ -n "$foo" -a -z "${foo/*$bar*}" ] ; then
echo exit 1
fi