列出所有环境变量,并显示它们是否被导出

列出所有环境变量,并显示它们是否被导出

(这个问题类似于这个这个但还有一个额外的要求,我想知道变量是否被导出)

我使用的是bashUbuntu 14.04.4 LTS。我想:

  • 列出所有环境变量
  • 对于每个变量,我想看看它是否被导出

此外,我想列出仅有的导出的环境变量。

答案1

使用declare内置函数:

$ help declare
declare: declare [-aAfFgilnrtux] [-p] [name[=value] ...]
    Set variable values and attributes.
        
    Declare variables and give them attributes.  If no NAMEs are given,
    display the attributes and values of all variables.
        
    Options:
      -f    restrict action or display to function names and definitions
      -F    restrict display to function names only (plus line number and
            source file when debugging)
      -g    create global variables when used in a shell function; otherwise
            ignored
      -p    display the attributes and value of each NAME
        
    Options which set attributes:
      -a    to make NAMEs indexed arrays (if supported)
      -A    to make NAMEs associative arrays (if supported)
      -i    to make NAMEs have the `integer' attribute
      -l    to convert NAMEs to lower case on assignment
      -n    make NAME a reference to the variable named by its value
      -r    to make NAMEs readonly
      -t    to make NAMEs have the `trace' attribute
      -u    to convert NAMEs to upper case on assignment
      -x    to make NAMEs export

因此:

$ declare -p
declare -- BASH="/usr/bin/bash"
declare -r BASHOPTS="checkwinsize:cmdhist:complete_fullquote:expand_aliases:extglob:extquote:force_fignore:histappend:interactive_comments:nullglob:progcomp:promptvars:sourcepath"
declare -ir BASHPID
declare -A BASH_ALIASES='()'
declare -a BASH_ARGC='()'
declare -a BASH_ARGV='()'
declare -A BASH_CMDS='()'
declare -- BASH_COMMAND
declare -r BASH_COMPLETION_COMPAT_DIR="/etc/bash_completion.d"
declare -a BASH_LINENO='()'
declare -a BASH_SOURCE='()'
declare -- BASH_SUBSHELL
declare -ar BASH_VERSINFO='([0]="4" [1]="3" [2]="42" [3]="1" [4]="release" [5]="x86_64-unknown-linux-gnu")'
declare -- BASH_VERSION="4.3.42(1)-release"
declare -x CDPATH=":/home/muru"
declare -x COLORTERM="gnome-terminal"
declare -- COLUMNS="237"
declare -- COMP_WORDBREAKS
declare -x CONFLOCAL="laptop"
declare -x DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/1000/bus"
declare -x DESKTOP_AUTOSTART_ID="10abca3e1337cb662146002998494759100000008000003"
declare -x DESKTOP_SESSION="gnome"
declare -a DIRSTACK='()'
declare -x DISPLAY=":0"
declare -x EDITOR="vim"

要查看刚刚导出的环境变量,请使用declare -px

$ declare -px
declare -x CDPATH=":/home/muru"
declare -x COLORTERM="gnome-terminal"
declare -x CONFLOCAL="laptop"
declare -x DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/1000/bus"
declare -x DESKTOP_AUTOSTART_ID="10abca3e1337cb662146002998494759100000008000003"
declare -x DESKTOP_SESSION="gnome"
declare -x DISPLAY=":0"
declare -x EDITOR="vim"
declare -x GDMSESSION="gnome"

或者使用外部命令,如envprintenv或者:

awk 'BEGIN{for (i in ENVIRON) {print i}}'
perl -e 'print "$_\n" for keys(%ENV)'
python -c 'import os; [print(k) for k in os.environ.keys()]'

相关内容