Problems running shelscripts in Windows

use std::process::Command;


fn main()
{
    let output = Command::new("echo")
        .arg("-c")
        .arg("Hello world")
        .output()
        .expect("Failed to execute command");
}

So this seems to run fine in Linux but not on Windows. I get this error:

thread 'main' panicked at 'Failed to execute command: Os { code: 2, kind: NotFound, message: "The system cannot find the file specified." }', src\main.rs:17:10
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
error: process didn't exit successfully: `target\debug\learning.exe` (exit code: 101)

Can you run echo -c "Hello world" from your Windows console directly, without Rust? If not, then, well, what did you expect?

fn main()
{
    let output = Command::new("cmd.exe")
        .arg("/c")
        .arg("echo")
        .arg("%userprofile%")
        .output()
        .expect("Failed to execute command");
    
    println!("{:?}", output.stdout);
}

Going by the code you posted I'm going to give you a potential heads-up: Don't assume that output.stdout is trivially transmutable into OsStr/OsString.

Summary

Also; just to be clear, this is not isolated to Windows. Running executables requires actual executables, and some commands one runs on a command line exist within the shell rather than as separate executables. (Commands that need to modify the shell's state are built-ins).

Whenever one wants to run a shell built-in, one must execute a shell and tell it to run the built-in command.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.