Skip to content

Instantly share code, notes, and snippets.

@curiositycasualty
Last active August 29, 2015 14:18
Show Gist options
  • Save curiositycasualty/af5be8e9aca29abfdaeb to your computer and use it in GitHub Desktop.
Save curiositycasualty/af5be8e9aca29abfdaeb to your computer and use it in GitHub Desktop.
#
# platform()
#
# Determine and return the current
# platform. Optionally return only the
# OS name with -o/--OS, or only the
# version with -v/--version.
#
function platform_ingestor() {
local argv="$@";
local -a uname;
local -a uname_args=("" "a" "v" "r" "p" "m");
local version;
local OS;
uname[0]="$(uname)";
for (( i=1; i<${#uname_args[@]}; i++ )); do
eval "uname[${i}]=\"\$(uname -\${uname_args[${i}]})\"";
done
case "${uname[0]}" in
SunOS)
OS="Solaris";
case "${uname[3]}" in
5.10)
version="10.$(head -1 /etc/release | perl -p -e 's/.*x_u(\d+).*/\1/g')";
;;
5.11)
version="${uname[2]}";
;;
*)
version="unknown";
;;
esac
;;
Darwin)
OS="mac-os-x";
version="$(sw_vers -productVersion)";
;;
Linux)
OS="Linux";
local lsb_all="$(lsb_release -a 2>&1 | grep -v "No LSB modules")";
local lsb_release="$(lsb_release -r 2> /dev/null | awk '{print $2}')";
case "$lsb_all" in
*Ubuntu*)
OS="$(echo $lsb_all | grep Distributor | awk '{print $3}')";
version="$lsb_release";
;;
*Red\ Hat*|*CentOS*|*command\ not\ found*)
unset redhat;
if [ ! -e "/etc/redhat-release" ]; then
break;
fi
local redhat_version="$(cat /etc/redhat-release | perl -p -e 's/.* release (\d+(\.\d+)*).*/\1/')";
OS="redhat";
version="$redhat_version";
;;
*Debian*)
local debian_version="$(cat /etc/debian_version)";
OS="Debian";
version="$debian_version";
;;
*)
version="unknown";
;;
esac
;;
AIX)
OS="AIX";
version="${uname[2]}.${uname[3]}";
;;
FreeBSD)
OS="FreeBSD";
version="$(echo "${uname[3]}" | perl -p -e 's/(\d+(\.\d+)*)-RELEASE.*/\1/')";
;;
*)
OS="unknown";
version="unknown";
;;
esac
if [[ ! "${OS}" == "unknown" ]]; then
# normalize the OS name to lowercase
OS="$(lowercase ${OS})";
# trim version to first 2 digits; open
# to this changing.
version="$(echo ${version} | cut -d. -f1,2)";
fi
if [[ "$argv" == *"-O"* ]] || [[ "$@" == *"--OS"* ]]; then
echo "$OS";
elif [[ "$argv" == *"-v"* ]] || [[ "$@" == *"--version"* ]]; then
echo "$version";
else
echo "${OS}-${version}";
fi
platform="$OS";
platform_version="$version";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment