Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

On my Linux box (Gentoo Linux 2.6.31 to be specific) I have noticed that the HOSTNAME environment variable is available in my shell, but not in scripts. For example,

$ echo $HOSTNAME

returns

xxxxxxxx.com,

but

$ ruby -e 'puts ENV["HOSTNAME"]'

returns

nil

On the other hand, the USER environment variable, for instance, is available both in the shell and in scripts.

I have noticed that USER appears in the list of environment variables that appears when I type

export

i.e.,

declare -x USER="infogrind"

but HOSTNAME doesn't. I suspect the issue has something to do with that.

My questions: 1) how can I make HOSTNAME available in scripts, and 2) for my better understanding, where is this variable initially set, and why is it not "exported"?

share|improve this question

$HOSTNAME is a Bash variable that's set automatically (rather than in a startup file). Ruby probably runs sh for its shell and it doesn't include that variable. There's no reason you can't export it yourself.

bash$ echo $HOSTNAME
foobar
bash$ sh -c 'echo $HOSTNAME'

bash$ export HOSTNAME
bash$ sh -c 'echo $HOSTNAME'
foobar

You could add the export command to one of your startup files, such as ~/.bashrc.

share|improve this answer
1  
It is usually better to use gethostname() because of this. – grawity Apr 19 '10 at 11:25
1  
The posix standard enumerates the environment variables you should expect on a posix-compliant systems, and HOSTNAME is not in the list: pubs.opengroup.org/onlinepubs/009695399/basedefs/… – qneill Apr 22 '15 at 20:56

You must log in to answer this question.