rust
のプログラムからlinuxのコマンドや自作のスクリプトファイルを実行する場合の備忘録
use std::process::Command;
fn main() {
match std::env::current_dir() { // カレントディレクトリを取得
Ok(x) =>
{
let output = Command::new("./user.sh") // 実行したいコマンド
.current_dir(x) // カレントディレクトリで実行
.output()
.expect("failed to execute process");
let hello = output.stdout;
println!("{}", std::str::from_utf8(&hello).unwrap());
},
Err(err) => {
eprintln!("{:?}", err);
},
}
}
- パスが通っているコマンドなら
.current_dir
の設定は要らないし、実行コマンドの頭に./
も要らない - パスは通ってるけど
ls
みたいにカレントディレクトリの状態が欲しい場合は必要。、(実行コマンドの頭に./
不要) - パスは通っていないけど、設置場所が決まっているなら 実行コマンドをフルパスで指定すればOK