Lets supose some bash shell script like:
#!/bin/bash
a=3
b=7
set -o posix
set
In this case, the execution of the set
variable or some other of the commands to print environment variables (env
,declare
… etc) outputs my a
and b
variables, plus a lot of variables (and functions) from the environment (PATH
, PWD
, TEMP
… etc).
Is there a way to print only those variables that have been defined during the script body?
Best Answer
You can store the list of variables at the beginning of the script and compare it with the value somewhere during the script. Beware that the output of commands like
set
isn't built to be unambiguous: something likeset | sed 's/=.*//'
doesn't work with variables whose values contain newlines. (In bash, it actually does for string variables, but not for arrays, and it also displays function code.) I think that the following snippet reliably lists the currently defined variables (in alphabetical order, to boot):Thus, set
initial_variables=…
at the beginning of the script, and compare with the later value. You can use something other thanecho
to act on the list directly.