-
-
Save hitrust/9f6e5b2d62859c7c3065d70c8d05081f to your computer and use it in GitHub Desktop.
Bash: Get the type of a variable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| typeofvar () { | |
| local type_signature=$(declare -p "$1" 2>/dev/null) | |
| if [[ "$type_signature" =~ "declare --" ]]; then | |
| printf "string" | |
| elif [[ "$type_signature" =~ "declare -a" ]]; then | |
| printf "array" | |
| elif [[ "$type_signature" =~ "declare -A" ]]; then | |
| printf "map" | |
| else | |
| printf "none" | |
| fi | |
| } | |
| # the basic type in bash is a string | |
| # there are no integers, nor booleans | |
| a="string" | |
| typeofvar a # string | |
| b=(array) | |
| typeofvar b # array | |
| declare -A c=([key]=value) | |
| typeofvar c # map | |
| f () { | |
| echo "is a function" | |
| } | |
| typeofvar f # none |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment