ShellScript
ShellScript

Reputation: 13

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

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

Upvotes: 1

Views: 125

Answers (2)

chepner
chepner

Reputation: 531758

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 all matches are anchored to the start of the string, and therefore the '^' anchor is not needed. (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 BREs (Basic Regular Expressions).

For more information, see -
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/expr.html#tag_20_42_13_01

Upvotes: 2

John Kugelman
John Kugelman

Reputation: 361849

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.

Upvotes: 1

Related Questions