我想保持我的.bashrc和.bash_login文件在版本控制,以便我可以在我使用的所有计算机之间使用它们。问题是我有一些操作系统特定的别名,所以我正在寻找一种方法来确定脚本是否在Mac OS X, Linux或Cygwin上运行。

在Bash脚本中检测操作系统的正确方法是什么?


当前回答

你可以使用以下方法:

OS=$(uname -s)

然后你可以在你的脚本中使用OS变量。

其他回答

对于我的.bashrc,我使用以下代码:

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

然后我会做如下的事情:

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

虽然很丑,但很管用。如果你愿意,你可以用case代替if。

我倾向于将.bashrc和.bash_alias保存在所有平台都可以访问的文件共享中。这就是我如何在我的.bash_alias中克服这个问题:

if [[ -f (name of share)/.bash_alias_$(uname) ]]; then
    . (name of share)/.bash_alias_$(uname)
fi

我有一个。bash_alias_linux的例子:

alias ls='ls --color=auto'

通过这种方式,我将特定于平台的代码和可移植的代码分开,你可以对.bashrc做同样的事情

我认为以下几点应该有用。不过我对win32不太确定。

if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        # ...
elif [[ "$OSTYPE" == "darwin"* ]]; then
        # Mac OSX
elif [[ "$OSTYPE" == "cygwin" ]]; then
        # POSIX compatibility layer and Linux environment emulation for Windows
elif [[ "$OSTYPE" == "msys" ]]; then
        # Lightweight shell and GNU utilities compiled for Windows (part of MinGW)
elif [[ "$OSTYPE" == "win32" ]]; then
        # I'm not sure this can happen.
elif [[ "$OSTYPE" == "freebsd"* ]]; then
        # ...
else
        # Unknown.
fi

你可以使用以下方法:

OS=$(uname -s)

然后你可以在你的脚本中使用OS变量。

uname

or

uname -a

如果你想了解更多信息