Environment variables are not accessible in bash script

67,072

That's because the HADOOP_HOME variable isn't exported:

$ cat foo.sh
#!/bin/bash
echo "HADOOP_HOME: $HADOOP_HOME"


$ HADOOP_HOME=/home/me/dist/hadoop
$ echo $HADOOP_HOME
/home/me/dist/hadoop

$ foo.sh
HADOOP_HOME: 

$ export HADOOP_HOME
$ foo.sh
HADOOP_HOME: /home/me/dist/hadoop

When you run a shell script, that script will run in its own bash instance (that's what the #!/bin/bash does) that is a child shell of the current one. Variables are not passed to child shells by default, only if they are exported. Think of each bash session as independent (they largely are). You usually don't want variables defined in one to pollute the environment of another. For those cases where that is necessary, use export.

Share:
67,072

Related videos on Youtube

Mehraban
Author by

Mehraban

Updated on September 18, 2022

Comments

  • Mehraban
    Mehraban over 1 year

    I ran into a weird problem. I put some env variables into .bashrc and it works as it should:

    echo $HADOOP_HOME
    /home/me/dist/hadoop
    

    But the env variable is not accessible when executing bash scripts. Suppose I create /tmp/sample.sh with below content:

    #! /bin/bash
    echo $HADOOP_HOME
    

    When I run above script, echoes an empty line:

    /tmp/sample.sh
       ‌
    
    • John N
      John N over 7 years
      Can you show the relevant part of your .bashrc? My guess is you're not exporting: export HADOOP_HOME=/home/me/dist/hadoop, when you run /tmpsample.sh` (which spawns a new bash with a new environment) HADOOP_HOME isn't in the new environment.
  • Frank Nocke
    Frank Nocke almost 3 years
    Not working under Ubuntu 21.04 :-/ Bash 5.1.4: BAR=' yes', echo $BAR (fine), export BAR, howdy.sh (has echo "BAR: $BAR" only outputs “BAR: ”
  • terdon
    terdon almost 3 years
    @FrankNocke please open a new question where you can show all relevant details. This isn't something that will be affected by bash version, really, so my guess is you are launching the script from a different session, but if you open a new question and explain exactly what you're doing, we should be able to figure it out.