How to detect the OS from a Bash script?

2020-01-23 03:00发布

I would like to keep my .bashrc and .bash_login files in version control so that I can use them between all the computers I use. The problem is I have some OS specific aliases so I was looking for a way to determine if the script is running on Mac OS X, Linux or Cygwin.

What is the proper way to detect the operating system in a Bash script?

21条回答
我想做一个坏孩纸
2楼-- · 2020-01-23 03:11

Try using "uname". For example, in Linux: "uname -a".

According to the manual page, uname conforms to SVr4 and POSIX, so it should be available on Mac OS X and Cygwin too, but I can't confirm that.

BTW: $OSTYPE is also set to linux-gnu here :)

查看更多
祖国的老花朵
3楼-- · 2020-01-23 03:12

The bash manpage says that the variable OSTYPE stores the name of the operation system:

OSTYPE Automatically set to a string that describes the operating system on which bash is executing. The default is system- dependent.

It is set to linux-gnu here.

查看更多
时光不老,我们不散
4楼-- · 2020-01-23 03:12

Doing the following helped perform the check correctly for ubuntu:

if [[ "$OSTYPE" =~ ^linux ]]; then
    sudo apt-get install <some-package>
fi
查看更多
唯我独甜
5楼-- · 2020-01-23 03:14

This should be safe to use on all distros.

$ cat /etc/*release

This produces something like this.

     DISTRIB_ID=LinuxMint
     DISTRIB_RELEASE=17
     DISTRIB_CODENAME=qiana
     DISTRIB_DESCRIPTION="Linux Mint 17 Qiana"
     NAME="Ubuntu"
     VERSION="14.04.1 LTS, Trusty Tahr"
     ID=ubuntu
     ID_LIKE=debian
     PRETTY_NAME="Ubuntu 14.04.1 LTS"
     VERSION_ID="14.04"
     HOME_URL="http://www.ubuntu.com/"
     SUPPORT_URL="http://help.ubuntu.com/"
     BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"

Extract/assign to variables as you wish

Note: On some setups. This may also give you some errors that you can ignore.

     cat: /etc/upstream-release: Is a directory
查看更多
Rolldiameter
6楼-- · 2020-01-23 03:16

You can use the following:

OS=$(uname -s)

then you can use OS variable in your script.

查看更多
姐就是有狂的资本
7楼-- · 2020-01-23 03:17

For my .bashrc, I use the following code:

platform='unknown'
unamestr=`uname`
if [[ "$unamestr" == 'Linux' ]]; then
   platform='linux'
elif [[ "$unamestr" == 'FreeBSD' ]]; then
   platform='freebsd'
fi

Then I do somethings like:

if [[ $platform == 'linux' ]]; then
   alias ls='ls --color=auto'
elif [[ $platform == 'freebsd' ]]; then
   alias ls='ls -G'
fi

It's ugly, but it works. You may use case instead of if if you prefer.

查看更多
登录 后发表回答