diff --git a/NEWS.md b/NEWS.md index 98fc1af270914..408dce72dd322 100644 --- a/NEWS.md +++ b/NEWS.md @@ -69,6 +69,7 @@ New library features * `@testset foo()` can now be used to create a test set from a given function. The name of the test set is the name of the called function. The called function can contain `@test` and other `@testset` definitions, including to other function calls, while recording all intermediate test results. ([#42518]) +* Keys with value `nothing` are now removed from the environment in `addenv` ([#43271]). Standard library changes ------------------------ diff --git a/base/cmd.jl b/base/cmd.jl index 70d22857522b7..9c9809454ad42 100644 --- a/base/cmd.jl +++ b/base/cmd.jl @@ -256,6 +256,7 @@ setenv(cmd::Cmd; dir="") = Cmd(cmd; dir=dir) Merge new environment mappings into the given [`Cmd`](@ref) object, returning a new `Cmd` object. Duplicate keys are replaced. If `command` does not contain any environment values set already, it inherits the current environment at time of `addenv()` call if `inherit` is `true`. +Keys with value `nothing` are deleted from the env. See also [`Cmd`](@ref), [`setenv`](@ref), [`ENV`](@ref). @@ -274,7 +275,11 @@ function addenv(cmd::Cmd, env::Dict; inherit::Bool = true) end end for (k, v) in env - new_env[string(k)::String] = string(v)::String + if v === nothing + delete!(new_env, string(k)::String) + else + new_env[string(k)::String] = string(v)::String + end end return setenv(cmd, new_env) end diff --git a/test/spawn.jl b/test/spawn.jl index ab8accf65e64a..c5669709677c2 100644 --- a/test/spawn.jl +++ b/test/spawn.jl @@ -817,6 +817,10 @@ end cmd2 = addenv(cmd, "FOO" => "foo2", "BAR" => "bar"; inherit=true) @test strip(String(read(cmd2))) == "foo2 bar" end + # Keys with value === nothing are deleted + cmd = Cmd(`$shcmd -c "echo \$FOO \$BAR"`, env=Dict("FOO" => "foo", "BAR" => "bar")) + cmd2 = addenv(cmd, "FOO" => nothing) + @test strip(String(read(cmd2))) == "bar" end