Conditional negation w/ bash

Viewed 64

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.

2 Answers

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 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
Related