2

This question already has an answer here:

I'm just learning the basics, including how to declare and mess around with variables. Is there a simple way to display a list of all the variables I've named? (Everything I've found by searching only talks about environment variables, which may be what I'm looking for, but probably not?)

marked as duplicate by lesmana, jofel, vonbrand, jasonwryan, Michael Mrozek Apr 25 '13 at 1:18

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

6

Running declare itself will give you a list of all the environmental variables in the current shell, including those you defined yourself. It will also include any functions, unless you use the -p option that skips them, but adds some extra noise.

1

There are 2 different types of variables (actually more than that, but in this context just 2), private and exported.

  • Private variables are variables which can be used in the shell (or script) but not by programs launched by the shell (or script).
    You can get a list of all variables including exported ones by using declare, typeset, or set. In bash all 3 do the same thing.

  • Exported variables can be used by both the shell or programs launched by it.
    You can get a list of exported variables by using env.

One key thing to note is when doing things such as this:

FOO="bar"
echo "$FOO"

$FOO is a private/non-exported variable. The shell is actually expanding $FOO to bar before it passes it to echo. So echo is actually being called as echo "bar".


You can export variables by doing export FOO, or export FOO="bar".
Additionally you can export a variable for just a single call to a program by adding the variable at the beginning of the command. For example

FOO="bar" cmd1
cmd2

cmd1 will have access to $FOO but cmd2 will not.

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