1
#!/bin/bash
env

This spits out a bunch of environment variables. $0, $@, $_, etc. are not output. Is there a way to dump them out, similar to how env or set dumps the rest of the environment? I don't mean anything like echo $0 or something, I want to see all of the possible special variables in their current state without directly calling all of them.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
ND Geek
  • 398
  • 6
  • 21
  • I am aware I can enumerate them myself. My point is I would like a function to do so. I could write `dump_vars` or something to do so, but I'm wanting to know if such a thing already exists. – ND Geek Sep 09 '18 at 02:15

2 Answers2

3

No, there is no existing function to automatically do this. You'll have to enumerate the variables yourself--but that's easy because there are only a few: What are the special dollar sign shell variables?

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 2
    @CharlesDuffy: Thanks for downvoting instead of fixing the link. I've fixed the link now. – John Zwinck Sep 09 '18 at 02:37
  • The question asked here is, "Is there a function that enumerates the special variables," not "What are the special variables?" – John Zwinck Sep 09 '18 at 02:38
  • As for "downvoting instead of fixing the link" -- this was originally effectively a link-only answer. Changing the link would be tantamount to completely rewriting the answer. The downvote was removed as soon as you corrected the link (even though I don't read the new one as on-topic for the OP's question either, it's at least not full of inaccuracies). – Charles Duffy Sep 09 '18 at 15:24
2

Built-in variables are included in the output to the set command. ($0 and $@ aren't variables at all, even special ones, so they aren't included -- but $_, $BASH_ALIASES, $BASH_SOURCE, $BASH_VERSINFO, $DIRSTACK, $PPID, and all the other things that are built-in variables are present).

$0, $*, $@, etc. are not built-in variables; they are special parameters instead. Semantics are quite different (you can use declare -p to print a variable's value, but not that of a special parameter; many built-in variables lose their special behavior if reassigned, whereas special parameters can never be the target of an assignment; etc).

http://wiki.bash-hackers.org/syntax/shellvars covers both built-in variables and special parameters.


If your goal is to generate a log of current shell state, I suggest the following:

(set; set -x; : "$0" "$@") &>trace.log

set dumps the things that are actually built-in variables (including $_), and the set -x log of running : "$0" "$@" will contain enough information to reproduce all special parameters which are based on your positional parameters ("$*", "$@", etc); whereas the output from set will include all other state.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441