3

I'm doing a basic script that asks the user some details about him/her. The fact is that I want to put the condition if the user doesn't put an age (number) the script warns with a message. I know there was somehow putting something like :

if [ $age != [0-9] ]

But it's not working whatsoever.

Any suggestion?

Ty.

kevin
  • 37
  • 5
  • ...I'm sure I've answered this question before, but the duplicates are mighty hard to search. – Charles Duffy Oct 20 '20 at 00:02
  • 1
    Does this answer your question? [How do I test if a variable is a number in Bash?](https://stackoverflow.com/questions/806906/how-do-i-test-if-a-variable-is-a-number-in-bash) – Lenna Oct 20 '20 at 02:00
  • @kevin : The _test_ command only tests for string equality/inequality. See `man test`. For wildcard pattern matching, you need the bash construct `[[ ... ]]`. – user1934428 Oct 20 '20 at 05:21

2 Answers2

7

Pick your favourite: all of these require the use of the double-bracket conditional construct

# is not all digits, regular expression
if [[ ! $age =~ ^[0-9]+$ ]]; ...

# contains a non-digit, regular expression
if [[ $age =~ [^0-9] ]]; ...

# contains a non-digit, glob pattern
if [[ $age == *[^0-9]* ]]; ...

# is not all digits, extended glob pattern
if [[ $age != +([0-9]) ]]; ...

In all of those methods, 0-9 can be replaced with the POSIX character class [:digit:]

if [[ $age == *[^[:digit:]]* ]]; ...

Documents:

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
5

Glenn has covered the bash-only answers. The POSIX way that'll work even with /bin/sh is to use case instead of if:

case $age in
  *[!0-9]*) echo "Age must not contain non-numeric digits";;
esac
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441