views:

267

answers:

4

In my script in bash, there are lot of variables, and I have to make something to save them to file. My question is how to list all variables declared in my script and get list like this:

VARIABLE1=abc
VARIABLE2=def
VARIABLE3=ghi

Is there some EASY way for this?

+5  A: 

set will output the variables, unfortunately it will also output the functions defines as well.

Luckily POSIX mode only outputs the variables:

( set -o posix ; set ) | less

Piping to less, or redirect to where you want the options.

So to get the variables declared in just the script:

( set -o posix ; set ) >/tmp/variables.before
source script
( set -o posix ; set ) >/tmp/variables.after
diff /tmp/variables.before /tmp/variables.after
rm /tmp/variables.before /tmp/variables.after

(Or at least something based on that :-) )

Douglas Leeder
You edited while I was posting. Nice call with the `-o posix` now a diff will only contain the variables.
ezpz
+2  A: 

If you can post-process, (as already mentioned) you might just place a set call at the beginning and end of your script (each to a different file) and do a diff on the two files. Realize that this will still contain some noise.

You can also do this programatically. To limit the output to just your current scope, you would have to implement a wrapper to variable creation. For example

store() {
    export ${1}="${*:2}"
    [[ ${STORED} =~ "(^| )${1}($| )" ]] || STORED="${STORED} ${1}"
}

store VAR1 abc
store VAR2 bcd
store VAR3 cde

for i in ${STORED}; do
    echo "${i}=${!i}"
done

Which yields

VAR1=abc
VAR2=bcd
VAR3=cde
ezpz
+1  A: 

The POSIX mode set by Douglas is a good one but unnecessary. You can just use:

env
paxdiablo
env will only work if you export the variables.
ezpz
+1  A: 

Try using a script (lets call it "ls_vars"):

  #!/bin/bash
  set -a
  env > /tmp/a
  source $1
  env > /tmp/b
  diff /tmp/{a,b} | sed -ne 's/^> //p'

chmod +x it, and:

  ls_vars your-script.sh > vars.files.save
Chen Levy