Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active May 19, 2023 01:00
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save CMCDragonkai/f1ed5e0676e53945429b to your computer and use it in GitHub Desktop.
Save CMCDragonkai/f1ed5e0676e53945429b to your computer and use it in GitHub Desktop.
Bash: Get the type of a variable
#!/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