How to find the name of the variables used in a script in bash

Viewed 193

I am trying to list the names of the variables that I have declared in my script, so I have been trying with different combinations of:

( set -o posix ; set ) | less

But I am not getting the result that I expected. It gives me an ouput with all variables in addition to my script´s variables. I do not know if I am using this command in the correct way. My intention is to only list the variables´ names that I have declared in my script and get an output like this:


VAR1
VAR2
VAR3
VAR4
…
2 Answers

A very simple solution as long as you use the prefix for your own variables. You should do this to avoid accidentally overwriting existing variables. Set defaults returns to a very long list of all defined variables not just yours, so you need to filter it by prefix.

#!/bin/bash
my_var1=aaa
my_var2=`ls`
export my_var3=bbb

compgen -v| awk -F= '/^my_/{print $1}'

# If you use sh shell it remains
#set |awk -F= '/^my_/{print $1}'

result

my_var1
my_var2
my_var3

EDIT: @Socowi rightly suggested using compgen -v for bash instead of set. Compgen is built into bash. Thanks.

set cannot be told to list only variables declared in a script. What can be done is to temporarily store defined variables at the script's beginning and filter them out at the end, so only variables defined in-between remain:

#!/bin/bash
set -o posix
set|sed s/=.\*// >/tmp/$$

VAR4=4
VAR3=3
VAR2=2
VAR1=1

set|sed s/=.\*//|grep -vf/tmp/$$
rm /tmp/$$

Note Socowi's valuable suggestions for improvement below.

Related