Using bash shell to auto-detect linux OS types(centos,debian,others)

#!/bin/bash
#linux_type.sh
os="";
grep "centos" /etc/issue -i -q
if [ $? = '0' ];then
os='centos'
fi

grep "debian" /etc/issue -i -q
if [ $? = '0' ];then
os='debian'
fi

if [ $os = "" ];then
echo "not a valid system os"
exit 1
fi
Save the above code as linux_type.sh,chmod +x ./linux_type.sh.Then,execute the bash script to get the result.

Good Luck & Best Wishes

4 thoughts on “Using bash shell to auto-detect linux OS types(centos,debian,others)

  1. This is a very poor solution. /etc/issue is very frequently modified by competent sysadmins specifically to REMOVE distinguishing info such as the OS release to make a hacker's life harder.

    Use this instead:

    #! /bin/sh
    ostype=
    [ -h /etc/dpkg/origins/default ] &" ] &"
    } || {
    [ -d /etc/dpkg/origins/ubuntu ] && ostype="ubuntu"
    [ -z "${ostype}" -a -d /etc/dpkg/origins/debian ] && ostype="debian"
    }
    } || {
    un=`uname -v`
    [ -n "${un}" ] &" in
    *untu* ) osname="ubuntu" ;;
    *) [ -f /etc/redhat-release ] &|| {
    osname="rhel"
    }
    }
    ;;
    esac
    }
    }
    : ${osname:=unknown}
    echo "$osname"

    • Wow, that's a very good and robust replacement for it. Thanks Kean. I'll update the post using your method.

  2. The formatting got all kinds of screwed up as it was posted as normal text. How do I mark text as code so special characters and formatting is retained?

Comments are closed.