Is it possible to "dump" all of the bash special variables via a command, like env?

400 Views Asked by At
#!/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.

2

There are 2 best solutions below

1
On BEST ANSWER

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.

2
On

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?