1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

rust でシステムコマンドを実行

Posted at

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
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?