How to print all non-environment variables?

These are all the variables I've added myself since the moment the shell started, like when doing:

read abc
# echo ${abc} => 123


# echo ${xyz} => 123

I want to print all of them, to know what was added to the memory, so I could clean it off.


1 Answer 1


If you're using Bash, this command will list the names of all shell variables that are not inherited by a child process and not part of the default slate:

diff -U 1 <(set -o posix ; set |cut -d= -f1) <(exec bash -ic 'set -o posix ; set' | cut -d= -f1)|grep '^[-][^-]'|cut -d- -f2|grep -vE '^(COLUMNS|HISTFILESIZE|HISTSIZE|LINES|PIPESTATUS)$'

This produces a list of all variable names in the current shell (with set), and a list of all variable names in a newly-created subprocess running the same shell, finds all those present in the first list and not the second (with diff, the last cut, and the first grep), and trims out some Bash-specific default variables that the subprocess won't have because it's not a user-facing shell. set -o posix makes set list only the variables and not functions.

It will omit both inherited environment variables and variables you've explicitly marked for export.

Swap out bash for your shell. You'll also need to change the list of ignored variables in the last grep, and can probably lose set -o posix. If your shell doesn't have process substitution, you'll need to use temporary files instead, or platform-specific access to file descriptors (like /dev/fd).

On the other hand, if all you want to do is clear out your own local variables and functions then

exec bash

will have that effect (while also re-reading some configuration files and potentially losing local changes to shell options).


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .