Conversation

Jarkko Sakkinen

A Rust question. Command::env_clear() has this example:

use std::process::Command;

Command::new("ls")
.env_clear()
.spawn()
.expect("ls command failed to start");

Isn't that like "do nothing" given that the instance Command was just created? I don't understand this example.

#rust #rustlang
3
0
2

@jarkko this is demonstrating the second part of the function's effect, "[...] and prevents inheriting any parent process environment variables"

0
0
0

@jarkko

`env_clear()` serves an important purpose even on a fresh Command instance. By default, a new Command inherits ALL environment variables from the parent process. `env_clear()` explicitly clears this inherited environment, giving you a clean slate.

So these two are different:

Command::new("ls") // Inherits env vars from parent

Command::new("ls").env_clear() // Starts with empty env

1
0
0

@jarkko

And perhaps a little explanation as to why they chose `ls` in this example:
this command can actually be affected by environment variables!

For example, LS_COLORS controls the colors of files/directories.

So env_clear() would make `ls` run with none of these customizations, giving you predictable "vanilla" behavior regardless of what env vars the parent process had set.

1
0
1
@mre Thanks this cleared it up for me!
0
0
2
@kornel Yeah so I ASSUMED that it must be along the lines what was described here but I don't want to live in a belief system so had to ask (and I'm glad that I got so many great answers here).
0
0
0