Bash 中的 `declare foo` 和 `foo=` 有什么区别?

Shu*_*eng 6 bash

Bashdeclare foofoo=Bash 中的区别是什么?

如果我打印出来的价值foo,那么它foofoo=""用于declare foofoo=分别。

foo和的值是否foo=""相等?如果不是,这些值之间有什么不同(两者-n-zfor 的[[ ... ]]行为相同)?

$ foo=
$ declare -p foo
declare -- foo=""
$ declare -p bar
bash: declare: bar: not found
$ declare bar
$ declare -p bar
declare -- bar
Run Code Online (Sandbox Code Playgroud)

ilk*_*chu 10

foo 和 foo="" 的值是否相等?如果没有,这些值之间如何可能有所不同

不,前者很像一个未设置的变量。您可以使用类似declare -x foo为变量设置标志而不设置值的方法,例如在这里标记foo为导出,以防它获得值。如果你能找到它的用途。(它实际上不会被导出到没有值的命令。)

使用[[ -v name ]](Bash/ksh/etc.) 或 [ "${var+set}" = set ](standard) 来区分未设置和设置但为空的变量:

$ unset foo
$ declare foo
$ declare -p foo
declare -- foo
$ [[ -v foo ]] && echo is set || echo not set
not set
$ echo ${foo+set}

$ unset foo
$ foo=
$ declare -p foo
declare -- foo=""
$ [[ -v foo ]] && echo is set || echo not set
is set
$ echo ${foo+set}
set
Run Code Online (Sandbox Code Playgroud)

此外,declare var在函数中使用使变量局部于函数,直接赋值不会,而是分配给全局变量:

$ foo=123 
$ f() { declare foo; declare -p foo; }
$ f; declare -p foo
declare -- foo
declare -- foo="123"

$ g() { foo=; declare -p foo; }
$ g; declare -p foo
declare -- foo=""
declare -- foo=""
Run Code Online (Sandbox Code Playgroud)

走出Bash,好像这里的Ksh和Bash类似,而在Zsh中,foo=和没有区别typeset foo,后者也把变量设置为空字符串:

% unset foo; typeset foo; typeset -p foo; [[ -v foo ]] && echo is set || echo not set
typeset foo=''
is set

% unset foo; foo=; typeset -p foo; [[ -v foo ]] && echo is set || echo not set
typeset foo=''
is set
Run Code Online (Sandbox Code Playgroud)

也可以看看: