从 Bash 脚本检测操作系统并通知用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10736923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:22:21  来源:igfitidea点击:

Detect OS from Bash script and notify user

stringbashsystemuname

提问by Graham

Using bash, I want to find the operating system and notify the user. I tried:

使用 bash,我想找到操作系统并通知用户。我试过:

OS='uname -s'
echo "$OS"
if [ "$OS" == 'Linux' ]; then
    echo "Linux"
else 
    echo "Not Linux"
fi

I just get

我只是得到

uname -s 
Not Linux

on the terminal, which is wrong. How do I correctly set the string to what uname returns?

在终端上,这是错误的。如何将字符串正确设置为 uname 返回的内容?

Thanks

谢谢

回答by William Pursell

Rather than single quotes, you probably meant to use backticks:

您可能打算使用反引号而不是单引号:

OS=`uname -s`

but you really want

但你真的想要

OS=$(uname -s)

Also, rather than an if statment, which will eventually become an if/else series, you might consider using case:

此外,您可以考虑使用 case,而不是最终将成为 if/else 系列的 if 语句:

case $( uname -s ) in
Linux) echo Linux;;
*)     echo other;;
esac

回答by robertmoggach

This will return the OS as requested - note that unameis not necessarily available on all OSes so it's not part of this answer.

这将根据要求返回操作系统 - 请注意,uname它不一定在所有操作系统上都可用,因此它不是此答案的一部分。

case "$OSTYPE" in
  linux*)   echo "linux" ;;
  darwin*)  echo "mac" ;; 
  msys*)    echo "windows" ;;
  solaris*) echo "solaris" ;;
  bsd*)     echo "bsd" ;;
  *)        echo "unknown" ;;
esac