Home > Blockchain >  Alternative of Equal Tidle operator(=~) when forced to use [ ] and [[ ]] is not supported
Alternative of Equal Tidle operator(=~) when forced to use [ ] and [[ ]] is not supported

Time:05-28

I am aware of a way of checking whether an input is a number with regex and =~ operator, however, a prerequisite is to use [[ ]]. What are the alternatives where [[ ]] is not supported and [ ] must be used which does not have the =~ operator?

I have found that option [ -o ] is being used, but how exactly this would work in this particular case with numbers? Ideally, I would like to get an example of how this line if ! [[ ${NUMBER} =~ ${RE} ]] would be written using [ ] instead of [[ ]].

Here is an example:

RE=^[0-9] $

read -p "Enter the number: " NUMBER



 if ! [[ ${NUMBER} =~ ${RE} ]];then

        echo 'Please enter a single positive number consisting of [0-9] digits' 1>&2

        exit 1

 fi

CodePudding user response:

You can use the POSIX utility expr for regular expression matching:

if expr "$number" : '[0-9][0-9]*$' > /dev/null; then
  echo "$number is a number"
fi

Note that you can omit the ^, since one quirk(?) of expr is that all matches are implicitly anchored to the start of the string. (If you wanted to disregard some prefix of the string, you would need to add .* to the beginning of the regular expression explicitly.)

expr outputs either the number of matched characters or the value of the first capture group. It also only supports POSIX basic regular expressions, so you'll note the verbose repetition [0-9][0-9]* in place of the operator to match 1 or more characters.

CodePudding user response:

If you're targeting POSIX sh you can use grep with -q for silent output, -x for whole line matches, and -E for extended regex syntax.

if ! printf '%s\n' "$number" | grep -qxE '[0-9] '; then
    exit 1
fi

If you need even more portability beyond POSIX, stick to basic regex syntax and redirect grep's output to /dev/null.

if ! printf '%s\n' "$number" | grep '^[0-9]\ $' >/dev/null 2>&1; then
    exit 1
fi

Both versions rely on $number being a one-line string.

  • Related