Skip to content

Instantly share code, notes, and snippets.

@Frankz
Forked from CMCDragonkai/typeofvar.sh
Created August 14, 2018 12:02
Show Gist options
  • Save Frankz/2ee2f24da392298c3832db22eb3f7a10 to your computer and use it in GitHub Desktop.
Save Frankz/2ee2f24da392298c3832db22eb3f7a10 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