In a bash shell process, I define some variables and functions here and there. So they are hard to track. How can I find all the self defined variables and functions to unset? Thanks.
-
Do you mean after all the shell initialization files have loaded? At what point do you consider it "you" versus /etc/profile or ~/.bashrc?Jeff Schaller– Jeff Schaller ♦2017-07-30 01:30:18 +00:00Commented Jul 30, 2017 at 1:30
-
I was interested in after. Now I am also interested in before, i.e. unset those defined in the initialization files.Tim– Tim2017-07-30 01:46:44 +00:00Commented Jul 30, 2017 at 1:46
3 Answers
Don't try to track which variables and functions you create. Instead, run the code in a subshell. When the subshell completes, all variables and functions defined within the subshell disappear.
In bash, one way to explicitly put commands in a subshell is to place the commands inside parens: (...). For example, let's define two variables and a function within a subshell and execute the function:
$ ( a=1; b=2; fn() { echo "a=$a b=$b"; }; fn )
a=1 b=2
After the subshell completes, all are erased:
$ fn
bash: fn: command not found
Quick and dirty: compare an "empty" environment with your current one
env -i bash set > baseline
set > now
diff baseline now
You can use compgen -v to list all variables defined within bash and compgen -A function to list all the functions
-
That lists all variables, not just the variables defined in a particular script.Gilles 'SO- stop being evil'– Gilles 'SO- stop being evil'2017-07-30 22:47:17 +00:00Commented Jul 30, 2017 at 22:47