3

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.

2

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

4

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

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

2 Comments

You'll need to escape the ., otherwise it will match 2c2 and the like.
correct, I had it in my post, just seems like it was rendered without it, thanks for remark, updated my solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.