List of all variables in a file in bash

When writing bash scripts, I like to write stand-alone functions that take an argument and perform operations based on this / these arguments, rather than declaring global variables in several different places in the code that reduces readability.

The problem arises when you have a function that needs to use multiple variables. Passing some function, like 10 variables, is just ugly, and a simple associative array can be used for this.

If we want to declare these variables in an external file, the "source" command allows you to import them all.

Then the question arises, how can I list the variables declared ONLY inside this file so that I can build an associative array with them? I was able to use the "compgen" combination and the loop to create associative arrays from the variable list, but how to list only the variables found inside the file, regardless of what they are called, so I can loop them and build my array?

+7
bash shell associative-array compgen
source share
3 answers

You can do egrep for some syntax for declaring variables in your file, and then get the variable name by cutting it, for example, as follows:

egrep '[a-zA-Z0-9"'\''\[\]]*=' /path/to/file |egrep -v '^#' |cut -d'=' -f1 |awk '{print $1}' 

If you have a file with content like this

 #!/bin/bash A="test" somerandomfunction () { echo "test function" B="test" } #C="test" DEF="test" GHI1="test" JKL[1]="test" JKL['a']="test" JKL["b"]="test" 

the output of the above command will look like this:

 A B DEF GHI1 JKL[1] JKL['a'] JKL["b"] 

Command Explanation:

  • The first egrep looks for strings containing any number and combination of lowercase ( az ) and / or uppercase ( az ) letters and / or square brackets ( \[\] ) and / or single ( '\'' ) and / or double ( " ) quotes followed by = .
  • The second egrep excludes lines beginning with # , as they are usually interpreted as comments and do not generate or set a variable.
  • The cut command disconnects everything from = to the end of the line.
  • The awk command prints the first appearance of something other than spaces or tabs, and therefore effectively cuts off the empty space in front of variable names.

The output of the command can be used in a loop or something like this:

 for VAR in $(egrep '[a-zA-Z0-9"'\''\[\]]*=' /path/to/file |egrep -v '^#' |cut -d'=' -f1 |awk '{print $1}'); do eval echo "\$${VAR}" done 
0
source share

this is one way to use awk

egrep "* =" file | awk 'BEGIN {FS = "="} {print $ 1}' | grep -v "#" | column -t

Explanation: Because the variables will have "=" to assign values, use this as the grep "* =" template from the file. After that, I use awk to declare the field separator as "=" and print anything before it using $ 1. The -t column is for aligning output to the left only.

Hope this helps.

0
source share

How to get variables directly from a file?

 VARLIST=$(cut -d= -f1 file_with_variables) 
0
source share

All Articles