Split And Join PATH Entries

env::split_paths breaks the PATH variable apart on the platform separator and env::join_paths rebuilds it, rejecting embedded separators.

RustConfig Management

Code

rustsnippet
21 lines
use std::env;

fn main() {
    // split_paths splits PATH by the platform separator: ':' on Unix, ';' on Windows
    let current = env::var_os("PATH").unwrap_or_default();
    let mut entries: Vec<_> = env::split_paths(&current).collect();
    println!("original entries: {}", entries.len());

    // after appending a directory, join_paths reassembles it with the platform separator
    entries.push("/opt/devtools/bin".into());
    let joined = env::join_paths(&entries).expect("entries contain no separators");

    // splitting it apart again verifies the last entry is the directory just appended
    let reopened: Vec<_> = env::split_paths(&joined).collect();
    println!("after join: {} entries", reopened.len());
    let last = reopened.last().map(|p| p.display().to_string());
    println!(
        "appended entry present: {}",
        last.as_deref() == Some("/opt/devtools/bin")
    );
}

How it works

Split And Join PATH Entries comes down to the function main.

What to watch for

  • Any imports it has point exclusively at standard-library modules.

Putting it to use

The signature you will reach for first is fn main()

The demo output is labeled (original entries:, after join:, appended entry present:), so each line traces straight back to the statement that printed it.

The core lines, annotated

let mut entries: Vec<_> = env::split_paths(&current).collect();
let reopened: Vec<_> = env::split_paths(&joined).collect();
let current = env::var_os("PATH").unwrap_or_default();

Interactive Tools for This Topic

FAQ

What does Split And Join PATH Entries print when run?
No setup needed: run the file and look for labeled lines like `original entries:`, `after join:`, `appended entry present:` in the output.