I need to check if the input argument of a bash script is a base ten number. How can I do?
-
2Possibly related to https://unix.stackexchange.com/questions/482822/bash-script-make-for-work and to its duplicate (homework questions from the last few days/weeks). – Kusalananda Nov 20 '18 at 13:27
-
Possible duplicate of How can I get my external IP address in a shell script? – Daniele Santi Nov 20 '18 at 13:31
-
3Is 5.0 a base 10 number? Or 4.2e2? – Jeff Schaller Nov 20 '18 at 13:39
2 Answers
Your can use pattern matching (improve on the regex if you don't want to accept a leading 0):
if [[ $num =~ ^[+-]?[1-9][0-9]*$ ]]
then
echo Decimal
else
echo Not decimal
fi

- 8,888
Compare it to itself while forcing base-ten interpretation. As seen in the shell Arithmetic manual:
Constants with a leading 0 are interpreted as octal numbers. A leading ‘0x’ or ‘0X’ denotes hexadecimal. Otherwise, numbers take the form [base#]n, where the optional base is a decimal number between 2 and 64 representing the arithmetic base, and n is a number in that base. If base# is omitted, then base 10 is used. When specifying n, the digits greater than 9 are represented by the lowercase letters, the uppercase letters, ‘@’, and ‘_’, in that order. If base is less than or equal to 36, lowercase and uppercase letters may be used interchangeably to represent numbers between 10 and 35.
Therefore if it's the first argument you can do...
EDITED AGAIN TO ACCOMMODATE NEGATIVE INPUT
#!/bin/bash
b=${1#-}
if [[ $b =~ ^[0-9]+$ ]]; then #If it's all numbers
a=$((10#$b)) #create a base 10 version
if [ "$a" == "$b" ]; then #if they LOOK the same...
echo "$b is Base 10!"; exit 1; fi; #It's base 10; exit.
fi
echo "$b is not base 10" #If it has letters or $a and $b look different, it's not base 10.
This code will take any input and tell you if it is base 10 or not. The arg is stripped of a negative sign first, then compared with $a non-numerically, because 012 -eq $((10#012)); but we don't want the script to tell us it's base ten because it isn't.
root@xxxx:~# ./testing.sh -124124
124124 is Base 10!
root@xxxx:~# ./testing.sh 58135
58135 is Base 10!
root@xxxx:~# ./testing.sh aksjflkfj929148
aksjflkfj929148 is not Base 10

- 419
-
1
-
-
@KuboLD Glad you liked my solution... But IMHO the adequate regexp is sufficient. – xenoid Nov 20 '18 at 18:47
-
@xenoid Agreed. I just like the chance to take something and run with it whenever I can. This was fun! – KuboMD Nov 20 '18 at 19:45