Search code examples
rustcommanddirectory-structure

Use ~ in std::process::Command


I am trying to use std::process::Command to run webdrivers programmatically installed at $HOME/.webdrivers. I don't want users to have to add the directory to their path, so I was hoping to be able to use something like

let geckodriver = Command::new("~/.webdrivers/geckodriver")
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;

But this doesn't seem to work. I'm getting the error for the executable not being there.

thread 'main' panicked at 'Could not start geckodriver: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/lib.rs:49:10

Anything helps!


Solution

  • Tilde expansion is a feature of the shell (bash, etc.) - the OS facilities that std::process::Command use do not expand tildes. So you will have to do it yourself.

    Get the HOME envvar using std::env::var_os, convert it to a Path, then join your executable path onto that.