Reputation: 24363
I need to create a BASH conditional that checks if any unusual characters are found. If any character is not one of these, the conditional returns true: c
, d
, f
, g
, h
, T
, ,
, ?
, !
. E.g.:
if [[ "$variable" contains something that is not [cdfghZ,?!] ]]
then
echo "The variable contains an unknown character."
fi
How can I check for characters not found in a list with a BASH conditional?
Upvotes: 2
Views: 125
Reputation: 189357
Good old case
has this built in, and is portable to all Bourne shells.
case $variable in *[!cdfghZ,?!]* )
echo "The variable contains an unknown character." >&2 ;;
esac
Upvotes: 4
Reputation: 531045
You can use extended patterns (which are used by default inside [[...]]
in bash
4.2 but need to be explicitly enabled in earlier versions):
shopt -s extglob # if necessary
if [[ $variable != +([cdfghZ,?!]) ]]; then
The pattern +(...)
matches a string containing one or more characters, each of which must match the pattern inside the parentheses. It is essentially equivalent to the regular expression [cdfghZ,?!]+
.
Upvotes: 2
Reputation: 785058
You can use globbing
:
[[ "$variable" == *[^cdfghT,?\!]* ]]
PS: !
needs to be used as \!
to escape history event expansion.
Upvotes: 4
Reputation: 241828
You can check with a regular expression:
if [[ $variable =~ [^cdfghT,?\!] ]] ; then
...
Upvotes: 3