{"id":13395478,"url":"https://github.com/rust-shell-script/rust_cmd_lib","last_synced_at":"2025-05-13T17:07:26.568Z","repository":{"id":35127273,"uuid":"209625062","full_name":"rust-shell-script/rust_cmd_lib","owner":"rust-shell-script","description":"Common rust command-line macros and utilities, to write shell-script like tasks in a clean, natural and rusty way","archived":false,"fork":false,"pushed_at":"2025-01-21T04:03:34.000Z","size":626,"stargazers_count":1105,"open_issues_count":11,"forks_count":39,"subscribers_count":11,"default_branch":"master","last_synced_at":"2025-04-24T01:52:41.510Z","etag":null,"topics":["bash","command-line","pipe","rust","script","shell"],"latest_commit_sha":null,"homepage":"https://docs.rs/cmd_lib/","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rust-shell-script.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-09-19T18:41:05.000Z","updated_at":"2025-04-22T03:34:57.000Z","dependencies_parsed_at":"2024-01-06T01:08:22.068Z","dependency_job_id":"76103e5c-e62f-4d84-859a-948f0fa3a7f6","html_url":"https://github.com/rust-shell-script/rust_cmd_lib","commit_stats":{"total_commits":532,"total_committers":7,"mean_commits":76.0,"dds":"0.12593984962406013","last_synced_commit":"c05052f053970438666ffdcd7df47db479f30c58"},"previous_names":[],"tags_count":23,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rust-shell-script%2Frust_cmd_lib","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rust-shell-script%2Frust_cmd_lib/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rust-shell-script%2Frust_cmd_lib/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rust-shell-script%2Frust_cmd_lib/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rust-shell-script","download_url":"https://codeload.github.com/rust-shell-script/rust_cmd_lib/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253990466,"owners_count":21995774,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bash","command-line","pipe","rust","script","shell"],"created_at":"2024-07-30T17:02:01.266Z","updated_at":"2025-05-13T17:07:26.546Z","avatar_url":"https://github.com/rust-shell-script.png","language":"Rust","readme":"# cmd_lib\n\n## Rust command-line library\n\nCommon rust command-line macros and utilities, to write shell-script like tasks\neasily in rust programming language. Available at [crates.io](https://crates.io/crates/cmd_lib).\n\n[![Build status](https://github.com/rust-shell-script/rust_cmd_lib/workflows/ci/badge.svg)](https://github.com/rust-shell-script/rust_cmd_lib/actions)\n[![Crates.io](https://img.shields.io/crates/v/cmd_lib.svg)](https://crates.io/crates/cmd_lib)\n\n### Why you need this\nIf you need to run some external commands in rust, the\n[std::process::Command](https://doc.rust-lang.org/std/process/struct.Command.html) is a good\nabstraction layer on top of different OS syscalls. It provides fine-grained control over\nhow a new process should be spawned, and it allows you to wait for process to finish and check the\nexit status or collect all of its output. However, when\n[Redirection](https://en.wikipedia.org/wiki/Redirection_(computing)) or\n[Piping](https://en.wikipedia.org/wiki/Redirection_(computing)#Piping) is needed, you need to\nset up the parent and child IO handles manually, like this in the\n[rust cookbook](https://rust-lang-nursery.github.io/rust-cookbook/os/external.html), which is often tedious\nand [error prone](https://github.com/ijackson/rust-rfcs/blob/command/text/0000-command-ergonomics.md#currently-accepted-wrong-programs).\n\nA lot of developers just choose shell(sh, bash, ...) scripts for such tasks, by using `\u003c` to redirect input,\n`\u003e` to redirect output and `|` to pipe outputs. In my experience, this is **the only good parts** of shell script.\nYou can find all kinds of pitfalls and mysterious tricks to make other parts of shell script work. As the shell\nscripts grow, they will ultimately be unmaintainable and no one wants to touch them any more.\n\nThis cmd_lib library is trying to provide the redirection and piping capabilities, and other facilities to make writing\nshell-script like tasks easily **without launching any shell**. For the\n[rust cookbook examples](https://rust-lang-nursery.github.io/rust-cookbook/os/external.html),\nthey can usually be implemented as one line of rust macro with the help of this library, as in the\n[examples/rust_cookbook.rs](https://github.com/rust-shell-script/rust_cmd_lib/blob/master/examples/rust_cookbook.rs).\nSince they are rust code, you can always rewrite them in rust natively in the future, if necessary without spawning external commands.\n\n### What this library looks like\n\nTo get a first impression, here is an example from\n[examples/dd_test.rs](https://github.com/rust-shell-script/rust_cmd_lib/blob/master/examples/dd_test.rs):\n\n```rust\nrun_cmd! (\n    info \"Dropping caches at first\";\n    sudo bash -c \"echo 3 \u003e /proc/sys/vm/drop_caches\";\n    info \"Running with thread_num: $thread_num, block_size: $block_size\";\n)?;\nlet cnt = DATA_SIZE / thread_num / block_size;\nlet now = Instant::now();\n(0..thread_num).into_par_iter().for_each(|i| {\n    let off = cnt * i;\n    let bandwidth = run_fun!(\n        sudo bash -c \"dd if=$file of=/dev/null bs=$block_size skip=$off count=$cnt 2\u003e\u00261\"\n        | awk r#\"/copied/{print $(NF-1) \" \" $NF}\"#\n    )\n    .unwrap_or_else(|_| cmd_die!(\"thread $i failed\"));\n    info!(\"thread {i} bandwidth: {bandwidth}\");\n});\nlet total_bandwidth = Byte::from_bytes((DATA_SIZE / now.elapsed().as_secs()) as u128).get_appropriate_unit(true);\ninfo!(\"Total bandwidth: {total_bandwidth}/s\");\n```\n\nOutput will be like this:\n\n```console\n➜  rust_cmd_lib git:(master) ✗ cargo run --example dd_test -- -b 4096 -f /dev/nvme0n1 -t 4\n    Finished dev [unoptimized + debuginfo] target(s) in 0.04s\n     Running `target/debug/examples/dd_test -b 4096 -f /dev/nvme0n1 -t 4`\n[INFO ] Dropping caches at first\n[INFO ] Running with thread_num: 4, block_size: 4096\n[INFO ] thread 3 bandwidth: 317 MB/s\n[INFO ] thread 1 bandwidth: 289 MB/s\n[INFO ] thread 0 bandwidth: 281 MB/s\n[INFO ] thread 2 bandwidth: 279 MB/s\n[INFO ] Total bandwidth: 1.11 GiB/s\n```\n\n### What this library provides\n\n#### Macros to run external commands\n- [`run_cmd!`](https://docs.rs/cmd_lib/latest/cmd_lib/macro.run_cmd.html) -\u003e [`CmdResult`](https://docs.rs/cmd_lib/latest/cmd_lib/type.CmdResult.html)\n\n```rust\nlet msg = \"I love rust\";\nrun_cmd!(echo $msg)?;\nrun_cmd!(echo \"This is the message: $msg\")?;\n\n// pipe commands are also supported\nlet dir = \"/var/log\";\nrun_cmd!(du -ah $dir | sort -hr | head -n 10)?;\n\n// or a group of commands\n// if any command fails, just return Err(...)\nlet file = \"/tmp/f\";\nlet keyword = \"rust\";\nrun_cmd! {\n    cat ${file} | grep ${keyword};\n    echo \"bad cmd\" \u003e\u00262;\n    ignore ls /nofile;\n    date;\n    ls oops;\n    cat oops;\n}?;\n```\n\n- [`run_fun!`](https://docs.rs/cmd_lib/latest/cmd_lib/macro.run_fun.html) -\u003e [`FunResult`](https://docs.rs/cmd_lib/latest/cmd_lib/type.FunResult.html)\n\n```rust\nlet version = run_fun!(rustc --version)?;\neprintln!(\"Your rust version is {}\", version);\n\n// with pipes\nlet n = run_fun!(echo \"the quick brown fox jumped over the lazy dog\" | wc -w)?;\neprintln!(\"There are {} words in above sentence\", n);\n```\n\n#### Abstraction without overhead\n\nSince all the macros' lexical analysis and syntactic analysis happen at compile time, it can\nbasically generate code the same as calling `std::process` APIs manually. It also includes\ncommand type checking, so most of the errors can be found at compile time instead of at\nruntime. With tools like `rust-analyzer`, it can give you real-time feedback for broken\ncommands being used.\n\nYou can use `cargo expand` to check the generated code.\n\n#### Intuitive parameters passing\nWhen passing parameters to `run_cmd!` and `run_fun!` macros, if they are not part to rust\n[String literals](https://doc.rust-lang.org/reference/tokens.html#string-literals), they will be\nconverted to string as an atomic component, so you don't need to quote them. The parameters will be\nlike `$a` or `${a}` in `run_cmd!` or `run_fun!` macros.\n\n```rust\nlet dir = \"my folder\";\nrun_cmd!(echo \"Creating $dir at /tmp\")?;\nrun_cmd!(mkdir -p /tmp/$dir)?;\n\n// or with group commands:\nlet dir = \"my folder\";\nrun_cmd!(echo \"Creating $dir at /tmp\"; mkdir -p /tmp/$dir)?;\n```\nYou can consider \"\" as glue, so everything inside the quotes will be treated as a single atomic component.\n\nIf they are part of [Raw string literals](https://doc.rust-lang.org/reference/tokens.html#raw-string-literals),\nthere will be no string interpolation, the same as in idiomatic rust. However, you can always use `format!` macro\nto form the new string. For example:\n```rust\n// string interpolation\nlet key_word = \"time\";\nlet awk_opts = format!(r#\"/{}/ {{print $(NF-3) \" \" $(NF-1) \" \" $NF}}\"#, key_word);\nrun_cmd!(ping -c 10 www.google.com | awk $awk_opts)?;\n```\nNotice here `$awk_opts` will be treated as single option passing to awk command.\n\nIf you want to use dynamic parameters, you can use `$[]` to access vector variable:\n```rust\nlet gopts = vec![vec![\"-l\", \"-a\", \"/\"], vec![\"-a\", \"/var\"]];\nfor opts in gopts {\n    run_cmd!(ls $[opts])?;\n}\n```\n\n#### Redirection and Piping\nRight now piping and stdin, stdout, stderr redirection are supported. Most parts are the same as in\n[bash scripts](https://www.gnu.org/software/bash/manual/html_node/Redirections.html#Redirections).\n\n#### Logging\n\nThis library provides convenient macros and builtin commands for logging. All messages which\nare printed to stderr will be logged. It will also include the full running commands in the error\nresult.\n\n```rust\nlet dir: \u0026str = \"folder with spaces\";\nrun_cmd!(mkdir /tmp/$dir; ls /tmp/$dir)?;\nrun_cmd!(mkdir /tmp/$dir; ls /tmp/$dir; rmdir /tmp/$dir)?;\n// output:\n// [INFO ] mkdir: cannot create directory ‘/tmp/folder with spaces’: File exists\n// Error: Running [\"mkdir\" \"/tmp/folder with spaces\"] exited with error; status code: 1\n```\n\nIt is using rust [log crate](https://crates.io/crates/log), and you can use your actual favorite\nlogger implementation. Notice that if you don't provide any logger, it will use env_logger to print\nmessages from process's stderr.\n\nYou can also mark your `main()` function with `#[cmd_lib::main]`, which will log error from\nmain() by default. Like this:\n```console\n[ERROR] FATAL: Running [\"mkdir\" \"/tmp/folder with spaces\"] exited with error; status code: 1\n```\n\n#### Builtin commands\n##### cd\ncd: set process current directory.\n```rust\nrun_cmd! (\n    cd /tmp;\n    ls | wc -l;\n)?;\n```\nNotice that builtin `cd` will only change with current scope\nand it will restore the previous current directory when it\nexits the scope.\n\nUse `std::env::set_current_dir` if you want to change the current\nworking directory for the whole program.\n\n##### ignore\n\nIgnore errors for command execution.\n\n##### echo\nPrint messages to stdout.\n```console\n-n     do not output the trailing newline\n```\n\n##### error, warn, info, debug, trace\n\nPrint messages to logging with different levels. You can also use the normal logging macros,\nif you don't need to do logging inside the command group.\n\n```rust\nrun_cmd!(error \"This is an error message\")?;\nrun_cmd!(warn \"This is a warning message\")?;\nrun_cmd!(info \"This is an information message\")?;\n// output:\n// [ERROR] This is an error message\n// [WARN ] This is a warning message\n// [INFO ] This is an information message\n```\n\n#### Low-level process spawning macros\n\n[`spawn!`](https://docs.rs/cmd_lib/latest/cmd_lib/macro.spawn.html) macro executes the whole command as a child process, returning a handle to it. By\ndefault, stdin, stdout and stderr are inherited from the parent. The process will run in the\nbackground, so you can run other stuff concurrently. You can call [`wait()`](https://docs.rs/cmd_lib/latest/cmd_lib/struct.CmdChildren.html#method.wait) to wait\nfor the process to finish.\n\nWith [`spawn_with_output!`](https://docs.rs/cmd_lib/latest/cmd_lib/macro.spawn_with_output.html) you can get output by calling\n[`wait_with_output()`](https://docs.rs/cmd_lib/latest/cmd_lib/struct.FunChildren.html#method.wait_with_output),\n[`wait_with_all()`](https://docs.rs/cmd_lib/latest/cmd_lib/struct.FunChildren.html#method.wait_with_all)\nor even do stream\nprocessing with [`wait_with_pipe()`](https://docs.rs/cmd_lib/latest/cmd_lib/struct.FunChildren.html#method.wait_with_pipe).\n\nThere are also other useful APIs, and you can check the docs for more details.\n\n```rust\nlet mut proc = spawn!(ping -c 10 192.168.0.1)?;\n// do other stuff\n// ...\nproc.wait()?;\n\nlet mut proc = spawn_with_output!(/bin/cat file.txt | sed s/a/b/)?;\n// do other stuff\n// ...\nlet output = proc.wait_with_output()?;\n\nspawn_with_output!(journalctl)?.wait_with_pipe(\u0026mut |pipe| {\n    BufReader::new(pipe)\n        .lines()\n        .filter_map(|line| line.ok())\n        .filter(|line| line.find(\"usb\").is_some())\n        .take(10)\n        .for_each(|line| println!(\"{}\", line));\n})?;\n```\n\n#### Macro to register your own commands\nDeclare your function with the right signature, and register it with [`use_custom_cmd!`](https://docs.rs/cmd_lib/latest/cmd_lib/macro.use_custom_cmd.html) macro:\n\n```rust\nfn my_cmd(env: \u0026mut CmdEnv) -\u003e CmdResult {\n    let args = env.get_args();\n    let (res, stdout, stderr) = spawn_with_output! {\n        orig_cmd $[args]\n            --long-option xxx\n            --another-option yyy\n    }?\n    .wait_with_all();\n    writeln!(env.stdout(), \"{}\", stdout)?;\n    writeln!(env.stderr(), \"{}\", stderr)?;\n    res\n}\n\nuse_custom_cmd!(my_cmd);\n```\n\n#### Macros to define, get and set thread-local global variables\n- [`tls_init!`](https://docs.rs/cmd_lib/latest/cmd_lib/macro.tls_init.html) to define thread local global variable\n- [`tls_get!`](https://docs.rs/cmd_lib/latest/cmd_lib/macro.tls_get.html) to get the value\n- [`tls_set!`](https://docs.rs/cmd_lib/latest/cmd_lib/macro.tls_set.html) to set the value\n```rust\ntls_init!(DELAY, f64, 1.0);\nconst DELAY_FACTOR: f64 = 0.8;\ntls_set!(DELAY, |d| *d *= DELAY_FACTOR);\nlet d = tls_get!(DELAY);\n// check more examples in examples/tetris.rs\n```\n\n### Other Notes\n\n#### Environment Variables\n\nYou can use [std::env::var](https://doc.rust-lang.org/std/env/fn.var.html) to fetch the environment variable\nkey from the current process. It will report error if the environment variable is not present, and it also\nincludes other checks to avoid silent failures.\n\nTo set environment variables, you can use [std::env::set_var](https://doc.rust-lang.org/std/env/fn.set_var.html).\nThere are also other related APIs in the [std::env](https://doc.rust-lang.org/std/env/index.html) module.\n\nTo set environment variables for the command only, you can put the assignments before the command.\nLike this:\n```rust\nrun_cmd!(FOO=100 /tmp/test_run_cmd_lib.sh)?;\n```\n\n#### Security Notes\nUsing macros can actually avoid command injection, since we do parsing before variable substitution.\nFor example, below code is fine even without any quotes:\n```rust\nfn cleanup_uploaded_file(file: \u0026Path) -\u003e CmdResult {\n    run_cmd!(/bin/rm -f /var/upload/$file)\n}\n```\nIt is not the case in bash, which will always do variable substitution at first.\n\n#### Glob/Wildcard\n\nThis library does not provide glob functions, to avoid silent errors and other surprises.\nYou can use the [glob](https://github.com/rust-lang-nursery/glob) package instead.\n\n#### Thread Safety\n\nThis library tries very hard to not set global states, so parallel `cargo test` can be executed just fine.\nThe only known APIs not supported in multi-thread environment are the\n[`tls_init!`](https://docs.rs/cmd_lib/latest/cmd_lib/macro.tls_init.html)/[`tls_get!`](https://docs.rs/cmd_lib/latest/cmd_lib/macro.tls_get.html)/[`tls_set!`](https://docs.rs/cmd_lib/latest/cmd_lib/macro.tls_set.html) macros, and you should only use them for *thread local* variables.\n\n\nLicense: MIT OR Apache-2.0\n","funding_links":[],"categories":["Rust","bash"],"sub_categories":["Rust libraries"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frust-shell-script%2Frust_cmd_lib","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frust-shell-script%2Frust_cmd_lib","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frust-shell-script%2Frust_cmd_lib/lists"}