Just out of curiosity, is there any way by which I can find the file from where a variable such as $PATH,$CDPATH is echoed from?

Second question: Also how does bash know about these variables? Is it env? If so, is this a file? Can such new custom variables be added?

up vote 1 down vote accepted

First question answer: $PATH variable gets constructed at login from number of files and the output that you see when you do echo $PATH is the result of the merged result (kept in memory).

To find in which file the PATH variable was set in (probably it will be in multiple files) you will have to consider the files that are read when you login. The list below may vary a bit from one distribution to another, but should be a good starting point.

/etc/profile, /etc/profile.d/*, /etc/bashrc, /etc/environment, ~/.bashrc, ~/.bash_profile, ~/.bash_login, ~/.profile. 

Second question answer As noted above variables are kept in memory, you can modify and add new ones as you wish. For example to add to already defined PATH:

[root@re ~]# PATH=$PATH:/opt/some/path
[root@re ~]# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/opt/some/path

The above is only valid for the current session. To make it permanent I will need to add it to one of the files that are being sourced during login.

Let's say I want to add JAVA_HOME and also ensure java binary file is in the system path variable. I will create new file called /etc/profile.d/my-java-env.sh with the following content.

[root@re ~]# cat /etc/profile.d/my-java-env.sh
# Here we are adding java bin folder to existing path.
PATH=$PATH:/usr/java/jdk1.8.0_20/bin
# Here we are creating new variable pointing to JAVA_HOME
JAVA_HOME=/usr/java/jdk1.8.0_20

For the above to become effective login anew.

$CDPATH By default on the distros I work with (Ubuntu, CentOS) the variable is empty (not set), but the same logic applies, if it's set then this has been probably done in one of the files sourced during login (as explained above).

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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