Shell – How to print only variables defined inside the shell script

scriptingshellvariable

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 like set | 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):

variables=$(tmp=$(declare -p +F); declare () { echo "${2%%=*}"; }; eval "$tmp")

Thus, set initial_variables=… at the beginning of the script, and compare with the later value. You can use something other than echo to act on the list directly.

initial_variables=" $(tmp=$(declare -p +F); declare () { echo "${2%%=*}"; }; eval "$tmp") "
…
( tmp=$(declare -p +F)
  declare () {
    case "$initial_variables" in
      *" $2 "*) :;; # this variable was present initially
      *) eval "set -- \"\$$2\" \"\$2\""; echo "locally defined $2=$1";;
    esac
  }
)