So, I'm setting up a bash script and want to parse arguments to certain flags using getopts. For a minimal example, consider the a script which has a flag, -M, and it takes y or n as an argument. If I use the following code:
#!/bin/bash
# minimalExample.sh
while getopts "M:" OPTION;
do
case ${OPTION} in
M)
RMPI=${OPTARG}
if ! [[ "$RMPI" =~ "^[yn]$" ]]
then
echo "-M must be followed by either y or n."
exit 1
fi
;;
esac
done
I get the following:
$ ./minimalExample.sh -M y
-M must be followed by either y or n.
FAIL: 1
However, if I use the following code instead
#!/bin/bash
# minimalExample2.sh
while getopts "M:" OPTION;
do
case ${OPTION} in
M)
RMPI=${OPTARG}
if [ -z $(echo $RMPI | grep -E "^[yn]$") ]
then
echo "-M must be followed by either y or n."
exit 1
else
echo "good"
fi
;;
esac
done
I get:
$ ./minimalExample2.sh -M y
good
Why doesn't minimalExample.sh
work?
quoting regexp in this context forces a string comparison.
change to
check following post for more details,
bash regex with quotes?