Skip to content

Instantly share code, notes, and snippets.

@mali30
Forked from CMCDragonkai/typeofvar.sh
Created May 1, 2020 15:47
Show Gist options
  • Save mali30/ecabf49c5d59872831ebdab56691a517 to your computer and use it in GitHub Desktop.
Save mali30/ecabf49c5d59872831ebdab56691a517 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