"env"和"set"之间有什么区别(在Mac OS X或Linux上)?

stu*_*kov 35 linux macos bash environment-variables

我得到类似的结果运行"env"和"设置".Set会给出更多结果 - 它是env的超集吗?

set的手册页不提供任何信息.这些命令如何工作,有什么区别?

int*_*tgr 51

长话短说:set可以看到shell局部变量,env不可以.

Shell可以有两种类型的变量:locals(只能从当前shell访问)和(导出的)环境变量,它们被传递给每个执行的程序.

由于set是一个内置的 shell命令,它还可以看到shell-local变量(包括shell函数).env另一方面是一个独立的可执行文件; 它只能看到shell传递给它的变量或环境变量.

当您键入一行时,a=1会创建一个局部变量(除非它已经存在于环境中).使用创建环境变量export a=1


小智 6

如果您想将set命令的输出限制为仅变量,您可以在 POSIX 模式下运行它:

type -a env set
help set
(set -o posix; set) | nl
Run Code Online (Sandbox Code Playgroud)

如果您需要更好地控制列出特定变量,您可以使用 Bash 内置函数,例如declarecompgen,或其他一些 Bash 技巧。

man bash | less -p '-A action$'  # info on complete & compgen

# listing names of variables
compgen -A variable | nl       # list names of all shell variables
echo ${!P*}                    # list names of all variables beginning with P

compgen -A export | nl         # list names of exported shell variables
export | nl                    # same, plus always OLDPWD
declare -px | nl               # same

declare -pr                    # list readonly variables

# listing names of functions           
compgen -A function | nl
declare -F | nl
declare -Fx | nl

# show code of specified function
myfunc() { echo 'Hello, world!'; return 0; }
declare -f myfunc  
Run Code Online (Sandbox Code Playgroud)