1

Is there a way to enumerate all the variables in a bash script and print out their values?

If that is not possible is there a way to print out the value of avariable give its name, ie from a string like 'ABC' print the value of $ABC if it has been assigned?

3
  • All the variables directly used by a script or all the variables available in the shell session? Commented Mar 24, 2015 at 11:37
  • Those used in the script, but if those available in the shell session can also be listed that will also be good. Commented Mar 24, 2015 at 11:39
  • The latter is easier. The former is somewhat impossible. That being said there isn't a way to "inspect" a script for the variables it will use (or expects to have set before being run or anything like that). Commented Mar 24, 2015 at 11:43

1 Answer 1

2

You can use compgen -v builtin:

while read -r line; do echo "$line=${!line}"; done < <(compgen -v)

Fore more details use:

help compgen

To list all variable created by your scripts (.bashrc etc):

{ set -o posix; set; }
Sign up to request clarification or add additional context in comments.

3 Comments

Yes both snippets will work from inside the script also.
Is there a way to restrict the output to only the variables in the script?
Did you try: { set -o posix; set; } from your script?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.