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.
Code
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(¤t).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(¤t).collect();
let reopened: Vec<_> = env::split_paths(&joined).collect();
let current = env::var_os("PATH").unwrap_or_default();
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.