如何只打印 shell 脚本中定义的变量?

Sop*_*rez 5 shell scripting variable

让我们假设一些 bash shell 脚本,例如:

#!/bin/bash 
a=3
b=7
set -o posix
set
Run Code Online (Sandbox Code Playgroud)

在这种情况下,执行变量set或其他一些打印环境变量的命令(envdeclare...等)输出 myab变量,以及环境中的许多变量PATH(和函数)( ,PWDTEMP...等) )。

有没有办法只打印脚本主体中定义的变量?

Sop*_*rez 1

comm基于存储之前和之后的所有变量的解决方案:

#!/bin/bash 

# Storing variables before:
set -o posix
set > $TMP/VariablesBefore.txt
sort $TMP/VariablesBefore.txt -o $TMP/VariablesBeforeSorted.txt

a=3
b=7

# Storing variables after:
set > $TMP/VariablesNow.txt
sort $TMP/VariablesNow.txt -o $TMP/VariablesNowSorted.txt

# Computing differences:
echo "The variables inside the script are: "
comm -3 $TMP/VariablesBeforeSorted.txt $TMP/VariablesNowSorted.txt
Run Code Online (Sandbox Code Playgroud)

好吧,仍然有一些变量,如_BASH_LINENO,但这是我已经达到的赌注。

请注意,此解决方案并非在所有情况下都适用,例如带有new line代码的非常长 (KB) 的变量或包含变量名称的变量。谢谢 MikeServ 的指点。