'How to interactively execute shell commands
I have been looking into executing shell commands with std::process::Command. I have a problem when these commands use arguments. What I would like to do is to have a loop and in each iteration ask for an input and execute that string (no matter what) as it is as a shell command, capture its output and then jump on to the next iteration.
I have tried by splitting the string with variable.split_whitespaces() but this doesn't seem to work.
As a refactor, I would like the equivalent in rust to this python code
import os
while True:
try:
command = input(">> ")
os.system(command)
except:
print("There was an error")
Solution 1:[1]
If you want to execute the input as a shell command, you have to give the command to a shell. The system-standard shell is usually available at /bin/sh and -c is how you execute a command from an argument. That would look roughly like this in Rust:
let output = std::process::Command::new("/bin/sh")
.args(["-c", the_user_input])
.output()?;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cdhowie |
