1

This has plagued me on and off for years. Can anyone explain why $(HOSTNAME) doesn't expand to the environment value HOSTNAME? Googling various combinations of "make", "hostname", "gmake", "not set" and so forth hasn't been fruitful for me.

jcomeau@intrepid:/tmp$ set | egrep 'HOSTNAME|USER'
HOSTNAME=intrepid
USER=jcomeau
jcomeau@intrepid:/tmp$ cat Makefile 
%.test:
    set | grep $*
%.env:
    echo $($*)
jcomeau@intrepid:/tmp$ make HOSTNAME.test
set | grep HOSTNAME
BASH_EXECUTION_STRING='set | grep HOSTNAME'
HOSTNAME=intrepid
jcomeau@intrepid:/tmp$ make HOSTNAME.env
echo 

jcomeau@intrepid:/tmp$ make USER.test
set | grep USER
BASH_EXECUTION_STRING='set | grep USER'
USER=jcomeau
jcomeau@intrepid:/tmp$ make USER.env
echo jcomeau
jcomeau
Mike Pennington
  • 41,899
  • 19
  • 136
  • 174
jcomeau_ictx
  • 37,688
  • 6
  • 92
  • 107

3 Answers3

8

This is the difference between a shell variable and an environment variable. Try running "export HOSTNAME" before your test and see the difference.

Also, compare the difference in output between "set" and "env".

cxreg
  • 11,088
  • 1
  • 20
  • 10
2

When you start a subprocess in a shell (perhaps by running the make command), it inherits the shell's original environment variables, plus all "exported" variables from inside the shell. If the shell's original environment didn't have $HOSTNAME and $HOSTNAME wasn't exported, it won't be in the environment of a spawned process.

Run export to see a list of exported variables. On my system, $HOSTNAME isn't in the exports by default. If you want HOSTNAME to be available in a spawned process, you can export HOSTNAME on the command line, or in your .bashrc/profile.

lunixbochs
  • 21,757
  • 2
  • 39
  • 47
0

If you want to export hostname you can use:

export SERVERIP=$(hostname --ip-address)
echo $SERVERIP
Dimitrios
  • 1,143
  • 11
  • 10