You can use regex to identify if a variable is a number or string in Linux bash.
Example:
Declare some variables with numbers and strings:
1 2 3 4 5 6 7 8 |
## declare some variables VAR1=1 VAR2=one VAR3=-10 VAR4=3.23 VAR5='&^$^$&*' VAR6=$(date) |
Create a function to test if a variable is a number or string:
1 2 3 4 5 6 7 8 9 |
## create a function to test if a variable is number or string isnumber() { if [[ $1 =~ ^[+-]?([0-9]+([.][0-9]*)?|\.[0-9]+)$ ]] then echo "$1 is number" else echo "$1 is string" fi } |
Test if a variable is number or string in Linux bash:
1 2 3 4 5 6 7 |
## test the function isnumber $VAR1 ## 1 is number isnumber $VAR2 ## one is string isnumber $VAR3 ## -10 is number isnumber $VAR4 ## 3.23 is number isnumber $VAR5 ## &^$^$&* is string isnumber $VAR6 ## Tue is string |