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


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

#! /bin/bash

When I run above script, echoes an empty line:

  • 2
    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. – John N Dec 10 '16 at 13:54

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

$ cat foo.sh

$ HADOOP_HOME=/home/me/dist/hadoop

$ foo.sh

$ 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.


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.