将值附加到go中环境变量的现有值

Appending values to existing values of environment variables in go

如何将另一个值附加到 go 环境变量的现有值?

如果 CGO_CXXFLAGS 的值为 "-I/blah/blah"

由于以下内容不起作用

$ go env -w CGO_CXXFLAGS="$CGO_CXXFLAGS -I/foo/bar"

我想找到一个合适的方法来 CGO_CXXFLAGS 得到值 "-I/blah/blah -I/foo/bar"

通过避免简单地重新设置所有值加上新值,例如:

$ go env -w CGO_CXXFLAGS="-I/blah/blah -I/foo/bar"

因为 go env <var_name> outputs the effective setting of the variable (i.e. not necessarily the default value), a reliable way to get at the current default value of an environment variable is using a subshell(假设 Bash shell):

$ (unset <var_name>; go env <var_name>)

然后,要设置您要使用的新值 command substitution:

$ go env -w <var_name>="$(unset <var_name>; go env <var_name>)<value_to_append>"

有关工作示例,请参阅以下带注释的日志:

# Write an initial default.
$ go env -w CGO_CXXFLAGS=-I/blah/blah

$ go env CGO_CXXFLAGS
-I/blah/blah

# Keep in mind that the default can be overridden by a currently set 
# environment variable.
$ export CGO_CXXFLAGS="-I/override/default"

$ go env CGO_CXXFLAGS
-I/override/default

# To print the default value even when it is being overridden,
# in a subshell, unset the environment variable and then run 'go env'. 
$ (unset CGO_CXXFLAGS; go env CGO_CXXFLAGS)
-I/blah/blah

# To set a new default value utilizing the existing default value.
#
# Note: if the default isn't being overridden, no warning will be printed.
$ go env -w CGO_CXXFLAGS="$(unset CGO_CXXFLAGS; go env CGO_CXXFLAGS) -I/foo/bar"
warning: go env -w CGO_CXXFLAGS=... does not override conflicting OS environment variable

# State after change...
# Default value
$ (unset CGO_CXXFLAGS; go env CGO_CXXFLAGS)
-I/blah/blah -I/foo/bar

# Overridden value
$ go env CGO_CXXFLAGS
-I/override/default

或者,您可以找到具有默认值的文件并直接解析它(go env GOENV 会告诉您文件位置),但我认为暂时取消设置环境变量并让 go env 做作业。


PowerShell 中的等价物:

# Write default.
PS > go env -w CGO_CXXFLAGS=-I/blah/blah
PS > go env CGO_CXXFLAGS
-I/blah/blah

# Override default.
PS > $Env:CGO_CXXFLAGS = "-I/override/default"
PS > go env CGO_CXXFLAGS
-I/override/default

# Print default.
PS > Start-Job {$Env:CGO_CXXFLAGS=''; go env CGO_CXXFLAGS} | Receive-Job -Wait
-I/blah/blah

# Append to default.
PS > go env -w CGO_CXXFLAGS="$(Start-Job {$Env:CGO_CXXFLAGS=''; go env CGO_CXXFLAGS} | Receive-Job -Wait) -I/foo/bar"
warning: go env -w CGO_CXXFLAGS=... does not override conflicting OS environment variable

# Final state.
PS > go env CGO_CXXFLAGS
-I/override/default

PS > Start-Job {$Env:CGO_CXXFLAGS=''; go env CGO_CXXFLAGS} | Receive-Job -Wait
-I/blah/blah -I/foo/bar