在我的主要机器 MacBook Pro 上,我有一个.bash_profile文件,我想在我的 Dreamhost linux 机器上原封不动地使用它。但是,有几行仅适用于 macOS,例如alias mvim="/Applications/MacVim.app/Contents/MacOS/MacVim".
在 bash 中是否有一种方法可以测试它是在 macOS 还是 Debian(或只是不是 macOS)下运行,并且在 macOS 下运行时只执行上面那行和其他几行?虽然这里的其他问题涉及如何找出正在使用的 Linux 发行版,但在这里我只需要知道我是在 macOS 还是 Linux 上运行,而了解 Linux 发行版的解决方案在 macOS 上不可用。
Tho*_*key 11
在 OSX 上,uname -s返回Darwin(大多数 Linuxuname程序返回Linux)。
作为一般规则(除了个人使用),uname对于不同的系统都有怪癖。在 中autoconf,脚本使用config.guess,它提供一致的信息。
例如在我的 Debian 7 中,
x86_64-pc-linux-gnu
Run Code Online (Sandbox Code Playgroud)
在 OSX El Capitan 中
x86_64-apple-darwin15.5.0
Run Code Online (Sandbox Code Playgroud)
您可以在 shell 中使用 if-then-else 语句或 case 语句。后者更容易维护,例如,
case $(config.guess) in
*linux*)
DoSomeLinuxStuff
;;
*apple-darwin*)
DoSomeMacStuff
;;
esac
Run Code Online (Sandbox Code Playgroud)
许多 Linux 发行版在 的输出中添加信息uname,但这仅在逐个案例的基础上有用。有没有为增加信息的标准。
对于我的 Debian 7:
$ uname -v
#1 SMP Debian 3.2.81-1
Run Code Online (Sandbox Code Playgroud)
而 OSX 则完全不同:
$ uname -v
Darwin Kernel Version 15.5.0: Tue Apr 19 18:36:36 PDT 2016; root:xnu-3248.50.21~8/RELEASE_X86_64
Run Code Online (Sandbox Code Playgroud)
进一步阅读:
Jul*_*ier 10
if [[ $(uname -s) == Linux ]]
then
doThis
else
doThat
fi
Run Code Online (Sandbox Code Playgroud)