终端启动后如何显示所有新变量?

终端启动后如何显示所有新变量?

在终端会话中我经常会做这样的事情:

$ Source="/bin"

$ AllFiles=$(ls $Source/* | wc -l)

$ echo $AllFiles
159

键入,echo $Source然后按echo $AllFiles等来显示我在当前终端会话中定义的变量是件乏味的事情。如果我使用,printenv我的屏幕上会充满我没有定义的东西。如果我使用,declare -p也会发生同样的事情。

我如何才能仅显示在此终端会话中定义的变量?

答案1

declare -p将显示环境变量之外定义的所有变量,其中包括您正在寻找的变量,以及您没有寻找的其他 121 个变量。

秘诀是在gnome-terminal打开时捕获默认变量并从当前变量列表中减去该变量以仅显示新变量。

使用listvar

listvar以下是创建该函数的说明。要查看该listvar函数的工作原理,请打开终端并输入:

$ listvar

$ hey="Hey World :/"

$ listvar
declare -- hey="Hey World :/"

$ Word=Something

$ Number=25

$ Ubuntu=16.04

$ listvar
declare -- Number="25"
declare -- Ubuntu="16.04"
declare -- Word="Something"
declare -- hey="Hey World :/"

创建listvar

将此添加到您的末尾~/.bashrc

# Below must be at end of ~/.bashrc
# Display newly created variables
function listvar () {

    # Get current variable list
    mapfile -t CurrVars <<< "$(declare -p)"

    # Loop through each current variable
    for CurrVar in "${CurrVars[@]}" ; do

        # Skip over unwanted variables that are dynamic
        [[ "$CurrVar" == "declare -a BASH_"*    ]] && continue
        [[ "$CurrVar" == "declare -a FUNCNAME"* ]] && continue
        [[ "$CurrVar" == "declare -a PIPESTAT"* ]] && continue
        [[ "$CurrVar" == "declare -- _=\"\""*   ]] && continue
#        [[ "$CurrVar" == "declare -- sh="*      ]] && continue

        # Skip over variables used in our listvar function
        [[ "$CurrVar" == "declare -a SaveVar"*  ]] && continue
        [[ "$CurrVar" == "declare -- SaveVar"*  ]] && continue
        [[ "$CurrVar" == "declare -a CurrVar"*  ]] && continue
        [[ "$CurrVar" == "declare -- CurrVar"*  ]] && continue
        [[ "$CurrVar" == "declare -a OldVar"*   ]] && continue
        [[ "$CurrVar" == "declare -- OldVar"*   ]] && continue
        [[ "$CurrVar" == 'declare -- _="SaveV'* ]] && continue
        [[ "$CurrVar" == 'declare -- _="listv'* ]] && continue

        OldVar=false
        for SaveVar in "${SaveVars[@]}" ; do
            # Is current variable existing at time of save?
            [[ "$CurrVar" == "$SaveVar" ]]         && { OldVar=true ; break ; }
        done
        [[ $OldVar == false ]] && echo "$CurrVar"
    done

} # listvar


# Empty array to prevent doubling everytime ~/.bashrc is resourced
SaveVars=()
# Save variable list before user creates new ones in shell
mapfile -t SaveVars <<< "$(declare -p)"

保存~/.bashrc文件并打开一个新的终端会话来使用listvar功能。

相关内容