0

Follow by

https://stackoverflow.com/questions/1809899/how-can-i-assign-the-output-of-a-function-to-a-variable-using-bash and How do I assign the output of a command to a variable?

I wrote

function getos(){
    # http://stackoverflow.com/a/27776822/1637673
    case "$(uname -s)" in
       Darwin)
         OS='mac'
         ;;
       Linux)
         OS='linux'
         ;;
       CYGWIN*|MINGW32*|MSYS*)
         OS='win'
         ;;
       # Add here more strings to compare
       # See correspondence table at the bottom of this answer
       *)
         OS='other'
         ;;
    esac
    echo $OS
}


echo $(getos)

OS=${getos}
echo ${OS} # show nothing
echo $OS   # show nothing
echo $(OS) # line 36

But bash common.sh got

linux


common.sh: line 36: OS: command not found

What's the problem ??

Mithril
  • 2,191
  • 3
  • 21
  • 30
  • If you edit the answer in the source, people will stare at it, searching for the error - like me. Only after reading the answer and investigating your edit history (which beginners can't do, AFAIK), I can see, what the original question was. It doesn't make sense to remove the part, which triggered the correct answer. – user unknown Jan 20 '18 at 09:34

2 Answers2

4

The underlying issue is that OS=${getos} expects getos to be a variable, not a function (it is a parameter expansion rather than a command substitution) - they're effectively different namespaces:

$ function foo() { echo foo; }
$ foo
foo
$ echo ${foo}

$

(i.e. variable foo is empty); whereas

$ foo=bar
$
$ foo
foo
$ echo ${foo}
bar

If you want OS to be a synonym for getos, you can use an alias:

alias OS='getos'

(although if you're using this in a script, be aware that alias expansion is only enabled in by default in interactive shells).

TL;DR: parentheses and braces are NOT interchangeable

steeldriver
  • 131,985
  • 21
  • 239
  • 326
3

bash tries to run the command OS and fails because

$(OS)

is Command Substitution whereas

${OS} # or
$OS

is Parameter Expansion.

The correct way to print the content of variable OS is echo $OS.

I suppose you however want to run your function, that assigns a value to your variable OS, and then print its content if not done by the function already:

getos
echo $OS
dessert
  • 39,392
  • 12
  • 115
  • 163
  • `echo ${OS}` and `echo $OS` show nothing – Mithril Jan 12 '18 at 14:59
  • My function return `echo $OS` , I want to set the return result to another variable , here just with same name OS . – Mithril Jan 12 '18 at 15:04
  • 1
    I think the issue is that `OS=${getos}` expects `getos` to be a *variable*, not a function - they're effectively different namespaces (i.e. unless you have a *variable* with the same name, `${getos}` is empty) – steeldriver Jan 12 '18 at 15:08
  • Oh, I am so careless. I looked `{` as `(` . Should be `OS=$(getos)` . – Mithril Jan 12 '18 at 15:15