问题
I am trying to parse a command in shell, and in one of the options I want to save in a variable if a string has "r", "w", "x", one of those, all of them, or a mix, but only these three. No other characters should be allowed!
I tried a case where:
$2 in *r*) ;; *w*) ;; *x*) ;; * ) echo no ;;
esac
But in this case if there is written zr it will pass, as it has an "r". I only want to make it pass as long as it has one of these three, the three of them, or two of them (any kind of combination), but no other characters.
回答1:
In BASH you can use regex for this check like this:
re='^[rwx]+$'
s='rw'
[[ $s =~ $re ]] && echo "yes" || echo "no"
yes
s='zr'
[[ $s =~ $re ]] && echo "yes" || echo "no"
no
Regex ^[rwx]+$ will allow 1 or more of r or w or x letters.
回答2:
With extended pattern matching in Bash (shopt -s extglob):
if [[ $var == +([rwx]) ]]; then
echo "Matches!"
else
echo "Does not match!"
fi
The +([rwx]) pattern is "one or more of r, w or x".
来源:https://stackoverflow.com/questions/41557871/filter-only-three-characters-in-shell