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,541
  • 3
  • 24
  • 30

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
  • 142,475
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
  • 40,956