warem
warem

Reputation: 1683

bash -- how to judge if a variable is a string or number

In bash shell, how do we judge if a variable is a string or number? Here, number could be an integer or a float. This link "How to judge a variable's type as string or integer" seems to only work integer.

Upvotes: 3

Views: 1043

Answers (2)

Peter Butkovic
Peter Butkovic

Reputation: 12149

Based on referred question, following does the job for me:

[[ $value =~ ^[0-9]+(\.[0-9]+)?$ ]]

Upvotes: 4

user2627497
user2627497

Reputation: 56

You could expand the proposed regular expression, dependent on the desired number format(s):

[[ $value =~ ^[0-9]+(\.[0-9]+)?$ ]] would recognize 2 or 2.4 as a number but 2. or .4 as a string.

[[ $value =~ ^(\.[0-9]+|[0-9]+(\.[0-9]*)?)$ ]] would recognize all 2, 2.4, 2. and .4 as numbers

Upvotes: 4

Related Questions