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.
Asked
Active
Viewed 838 times
3
-
1And you didn't try adapting that for floats? – Mat Jul 28 '13 at 11:42
-
possible duplicate of [How do I test if a variable is a number in bash?](http://stackoverflow.com/questions/806906/how-do-i-test-if-a-variable-is-a-number-in-bash) – Charles Duffy Jul 28 '13 at 14:28
2 Answers
4
Based on referred question, following does the job for me:
[[ $value =~ ^[0-9]+(\.[0-9]+)?$ ]]

cmbuckley
- 40,217
- 9
- 77
- 91

Peter Butkovic
- 11,143
- 10
- 57
- 81
-
1You'll need to escape the `.`, otherwise it will match `2c2` and the like. – cmbuckley Jul 28 '13 at 11:50
-
correct, I had it in my post, just seems like it was rendered without it, thanks for remark, updated my solution – Peter Butkovic Jul 28 '13 at 11:55
4
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

user2627497
- 56
- 1