0

I'm used to doing something like this in my bash scripts to echo output to a variable:

myvar=`echo $OSTYPE`
echo "my os is of type: ${myvar}"

On this current project however I'm using sh, which on my Ubuntu instance doesn't appear to be symlinked to bash. I say that because the above code echoes nothing for ${myvar} when I have the /bin/sh shebang at top.

So I assume echo $OSTYPE is not the way to go in sh? If not, how can I do something similar? (I've tried to echo $(myvar) but that didn't work either.)

  • 2
    It's not the way to go in any shell language. myvar="$OSTYPE" – Patrick Oct 20 '14 at 16:57
0

The following seems to work just fine in my sh :

$ myvar="test"
$ echo "My var is $myvar."
My var is test.

There is no need to echo the value of the variable and catch it again in another. Here is a little bit more information on variable assignments.

The thing is, OSTYPE is not defined in sh's environment. You'll have to pass it when running your script. So, instead of running...

$ /bin/sh yourscript.sh
or
$ ./yourscript.sh

You should run:

$ OSTYPE=$OSTYPE /bin/sh yourscript.sh
or
$ OSTYPE=$OSTYPE ./yourscript.sh

Of course, this assumes that the parent shell, in which you type the above command, has an OSTYPE variable. While bash does, it is not the case of every shell. Instead of $OSTYPE, you might however be able to use uname:

$ OS=$(uname -o)
$ echo "My OS is $OS."
My OS is GNU/Linux.
$ echo "My OS is $(uname -o)."
My OS is GNU/Linux.

On my machine, this sets the OS variable to GNU/Linux, instead of linux-gnu (which is the content of my OSTYPE).

As a side note, I'm guessing an equivalent of your code could be :

$ myvar="$(echo $OSTYPE)"
$ echo "My var is $myvar."
My var is linux-gnu
  • Thank you. I don't suppose there's an OSTYPE semi-equivalent outside of the bash/bourne shell? Maybe uname will do? – jkj2000 Oct 20 '14 at 17:20
  • @jkj2000 You could use $(uname -o) instead. I updated my answer. – John WH Smith Oct 20 '14 at 17:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.