Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out where an environment variable was last set in bash

Okay I know there is a bash debugger. But what I'm seeking is if I had an environment variable in one of my startup scripts and I don't know how it was set or where it might be, is there a way to find it other than exhaustively searching the scripts?

I mean is there a mechanism/tool that provides such a thing? Does bash keep track of variable setting locations?

Even though this might not seem very important but it crossed my mind the other day when I was helping a friend install OpenCL and the package supposedly set the variable $ATISTREAMSDKROOT automatically. Anyway the package was supposed to add a file to /etc/profile.d to allow for setting the variable, but it didn't. And luckily the variable came out blank.

But I was wondering if it hadn't come out blank, and the package added it to some random file, I would have probably had no way of telling where it is other than looking for it.

Of course I know one could write a sed command or two and search through the scripts but I'd consider that exhaustive search :D

like image 556
omarzouk Avatar asked Mar 14 '11 14:03

omarzouk


People also ask

How do I know where environment variable is set?

Enter echo $VARIABLE. Replace VARIABLE with the name of the environment variable you set earlier. For example, to check if MARI_CACHE is set, enter echo $MARI_CACHE. If the variable is set, its value is displayed in the terminal window.

Where is $PATH variable stored?

The PATH environment variable is an important security control. It specifies the directories to be searched to find a command. The default systemwide PATH value is specified in the /etc/profile file, and each user normally has a PATH value in the user's $HOME/. profile file.


1 Answers

One option would be to start an instance of bash with:

bash -x

... and look for where the variable is set in that output. To redirect that output to a file, you could do:

bash -x -ls -c "exit" 2> shell-startup-output

You should see in the output where each file is sourced.

like image 159
Mark Longair Avatar answered Nov 16 '22 02:11

Mark Longair