#subprocess #shell #macro

sh-inline

Macros to run inline shell (bash) script

7 unstable releases (3 breaking)

0.4.0 Nov 15, 2022
0.3.0 Jun 27, 2022
0.2.3 Jun 23, 2022
0.2.2 May 4, 2022
0.1.0 Aug 26, 2020

#1834 in Rust patterns

Download history 6/week @ 2023-12-07 3/week @ 2023-12-14 1/week @ 2023-12-21 11/week @ 2023-12-28 49/week @ 2024-01-04 15/week @ 2024-01-18 23/week @ 2024-01-25 24/week @ 2024-02-01 75/week @ 2024-02-08 74/week @ 2024-02-15 75/week @ 2024-02-22 20/week @ 2024-02-29 41/week @ 2024-03-07 140/week @ 2024-03-14 3/week @ 2024-03-21

214 downloads per month

MIT/Apache

13KB
213 lines

sh-inline

This was forked from https://github.com/tcr/commandspec - there were various unreviewed PRs (e.g. https://github.com/tcr/commandspec/pull/10) and this version also has various other changes:

  • Focuses just on the macros for execution and doesn't try to include other things like killing subprocesses.
  • Documentation
  • Uses "bash strict mode" http://redsymbol.net/articles/unofficial-bash-strict-mode/
  • Supports Path objects directly (including quoting non-UTF8 values)
  • Removes non-bash macros (and Windows support) - for now

License

MIT or Apache-2.0, at your option.


lib.rs:

Macros to run bash scripts inline in Rust

In many cases it's convenient to run child processes, particularly via Unix shell script. Writing the Rust code to use std::process::Command directly will get very verbose quickly. You can generate a script "manually" by using e.g. format!() but there are some important yet subtle things to get right, such as dealing with quoting issues.

This macro takes Rust variable names at the start that are converted to a string (quoting as necessary) and bound into the script as bash variables.

Further, the generated scripts use "bash strict mode" by default, i.e. set -euo pipefail.

use sh_inline::*;
let foo = "variable with spaces";
bash!(r#"test "${foo}" = 'variable with spaces'"#, foo)?;

This generates and executes bash script as follows:

set -euo pipefail
foo="variable with spaces"
test ${foo} = 'variable with spaces'

Related crates

xshell is a crate that does not depend on bash, and also supports inline formatting.

Dependencies

~2–14MB
~137K SLoC