7

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

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?

Thanks

2 Answers 2

13

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 $( uname -s ) in
Linux) echo Linux;;
*)     echo other;;
esac
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for the answer! That is the first time I've ever noticed the difference between a ` and a ' :D
That's just one reason $() is superior :)
@chepner. The quotes are not necessary, even if the output contains spaces. $() is a quoting mechanism, so putting it in double quotes is redundant. Consider: a='foo bar'; case $( echo foo bar ) in; $a):;; esac
$() only quotes when used immediately to the right of = in a variable assignment. Try /bin/ls $(date) to see the lack of quoting by $(). This probably doesn't affect the answer given above much, since uname -s almost always outputs a single word (without spaces).
$() doesn't perform the quoting at all. Bash does not word-split on the right side of a variable assignment.
|
2

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

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

3 Comments

-1 There is nothing Bash-specific here but it also does not solve the OP's problem at all.
his question says "Using bash, I want to find the operating system and notify the user" uname is not OS agnostic - it won't work on some OSes. This solution should work on bash on most. You're correct that it's not bash specific so i've adjusted the answer.
"$OSTYPE", distinguishes between android phones and full Linux installations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.