0

Let's say I have something like this:

#!/bin/bash
var1=1
var2='two'
third='cat'
abcd='dog'
.
.
.
.
something='else'
env

Now I want print all variables declared inside my script.
I tried env, but yea... it prints environment vars not my local ones..
Also cat /proc/$$/environ doesnot give me what I want as its equal to env.
Running my script with more debug info bash -x ./myscript.sh does not suit me.
Is there any trick to list all vars with their values?

  • use comand `set` – Wiimm Aug 26 '22 at 22:03
  • There's nothing that will just print the variables defined in the script. `set` will print them, but it also prints all the built-in variables and inherited environment variables. – Barmar Aug 26 '22 at 22:13

2 Answers2

1

You can use this solution: https://stackoverflow.com/a/63459116

#!/bin/bash

set_before=$( set -o posix; set | sed -e '/^_=*/d' )

var1=1
var2='two'
third='cat'
abcd='dog'
something='else'

set_after=$( set -o posix; unset set_before; set | sed -e '/^_=/d' )
diff  <(echo "$set_before") <(echo "$set_after") | sed -e 's/^> //' -e '/^[[:digit:]].*/d'
lmcapacho
  • 171
  • 1
  • 6
0

Depending on your use case, you might not need to save the "before" set output and then compare it with an "after" output.

If all your variables have some basic pattern, a set | grep may be enough.

The built-in variables all have uppercase names. I always start my script variable names in lowercase. So a simple

set | grep '^[a-z].*='

lists all the variables defined so far in the script.

This would also parse functions, but since set prints them indented, these lines will not start with a lowercase letter and will be ignored.

If you don't want the functions to also go through grep, use the Posix option as in all other answers:

( set -o posix; set | grep '^[a-z].*=' )
mivk
  • 13,452
  • 5
  • 76
  • 69