4

How can I display a list of shell variables in Bash, not including functions, which often clutter the output, because of the many related to completion?

I have examined declare, and it has an option for limiting the output to functions (declare -f), but not for limiting the output to "plain" shell variables?

Kusalananda
  • 333,661
Shuzheng
  • 4,411

1 Answers1

6

The command compgen -v will display a list of names of shell variables in the current bash shell session. Also, declare -p, which lists the attributes and values of all variables in a form that is (almost always) suitable for shell input, does not list functions.

Kusalananda
  • 333,661
  • Thank you. What I would have anticipated the most, is the output of declare without functions, i.e. just name/value pairs. Are functions also considered variables, or why does declare include them? – Shuzheng Mar 26 '21 at 10:06
  • @Shuzheng The bash shell stores functions as a special type of variable. Other shells do not do that. – Kusalananda Mar 26 '21 at 10:23
  • By special type of variable - what do you mean? Will you elaborate, although off-topic for the question? I see that functions and variables can exist with the same name, i.e. f() { echo foo; }; f=bar – Shuzheng Mar 26 '21 at 10:30
  • @Shuzheng The shell still keeps an illusion of a separate name-space for variables and functions (which it must do). If you export a function (export -f f) and use printenv, you would see BASH_FUNC_f%% as the name. – Kusalananda Mar 26 '21 at 10:33
  • Why must it do that? Why export a function? Child processes are not able to call it, anyway? – Shuzheng Mar 26 '21 at 11:33
  • 1
    @Shuzheng Must do what? I the child process is a bash shell, it can call the exported function. But you are getting side-tracked now. Your follow-up question was about the names of functions. I gave you an example that showed that bash stores functions as variables. I used an exported function as an example so that I could use the external utility printenv to view its name. If I had used built-in utilities, bash would have made it look like the function was just called f. – Kusalananda Mar 26 '21 at 11:54
  • I see, thanks. What i meant was "The shell still keeps an illusion of a separate name-space for variables and functions (which it must do)". What do you mean here? – Shuzheng Mar 26 '21 at 12:25
  • @Shuzheng Exactly what I wrote. If you ask bash about what the currently defined functions are, it will list these for you using the names you have given them, even if these names seems to be the same as some variables' names. I.e., it maintains the illusion of separate name spaces for variables and functions, even though it actually stores functions as "special variables". If you have further questions about this particular topic, I suggest that you ask a separate question. – Kusalananda Mar 26 '21 at 12:29