Last active
May 19, 2023 01:00
-
-
Save CMCDragonkai/f1ed5e0676e53945429b to your computer and use it in GitHub Desktop.
Bash: Get the type of a variable
This file contains 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