@@ -6,45 +6,44 @@ import pf.Cmd
66# Different ways to run commands like you do in a terminal.
77
88main ! = |_args | {
9- # Simplest way to execute a command (prints to your terminal).
10- exec_result = Cmd . exec !("echo ", [" Hello" ])
11- match exec_result {
12- Ok ({}) => {}
13- Err (_ ) => Stdout . line !("Error running echo" )
14- }
15-
16- # To execute and capture the output (stdout and stderr) without inheriting your terminal.
17- output_result = Cmd.exec_output!(Cmd.args(Cmd.new(" echo" ), [" Hi " ]))
18- match output_result {
19- Ok(cmd_output) => Stdout.line!(" {stderr_utf8_lossy: \" ${cmd_output.stderr_utf8_lossy}\" , stdout_utf8: \" ${cmd_output.stdout_utf8}\" }" )
20- Err (_ ) => Stdout . line !("Error capturing output" )
21- }
22-
23- # To run a command with environment variables.
24- env_cmd = Cmd.args(
25- Cmd.envs(
26- Cmd.env(
27- Cmd.clear_envs(Cmd.new(" env" )),
28- " FOO " ,
29- " BAR " ,
30- ),
31- [(" BAZ " , " DUCK " ), (" XYZ " , " ABC " )],
32- ),
33- [" - v" ],
34- )
35- env_result = Cmd.exec_cmd!(env_cmd)
36- match env_result {
37- Ok({}) => {}
38- Err(_) => Stdout.line!(" Error running env" )
39- }
40-
41- # To execute and just get the exit code (prints to your terminal).
42- # Prefer using `exec!` or `exec_cmd!`.
43- exit_result = Cmd.exec_exit_code!(Cmd.args(Cmd.new(" cat" ), [" non_existent. txt " ]))
44- match exit_result {
45- Ok(exit_code) => Stdout.line!(" Exit code: ${exit_code. to_str ()}" )
46- Err(_) => Stdout.line!(" Error getting exit code" )
47- }
48-
49- Ok({})
9+ # Simplest way to execute a command (prints to your terminal).
10+ Cmd . exec !("echo ", [" Hello" ])?
11+
12+ # To execute and capture the output (stdout and stderr) without inheriting your terminal.
13+ cmd_output =
14+ Cmd . new ("echo ")
15+ . args ([" Hi" ])
16+ . exec_output !()?
17+
18+ Stdout . line !("${Str . inspect (cmd_output )}")?
19+
20+ # To run a command with environment variables.
21+ Cmd . new ("env ")
22+ . clear_envs () # You probably don't need to clear all other environment variables, this is just an example.
23+ . env (" FOO" , " BAR" )
24+ . envs ([(" BAZ" , " DUCK" ), (" XYZ" , " ABC" )]) # Set multiple environment variables at once with `envs`
25+ . args ([" -v" ])
26+ . exec_cmd !()?
27+
28+ # To execute and just get the exit code (prints to your terminal).
29+ # Prefer using `exec!` or `exec_cmd!`.
30+ exit_code =
31+ Cmd . new ("cat ")
32+ . args ([" non_existent.txt" ])
33+ . exec_exit_code !()?
34+
35+ Stdout . line !("Exit code: ${exit_code. to_str ()}" )?
36+
37+ # TODO add exec_output_bytes
38+
39+ # To execute and capture the output (stdout and stderr) in the original form as bytes without inheriting your terminal.
40+ # Prefer using `exec_output!`.
41+ #cmd_output_bytes =
42+ # Cmd.new(" echo" )
43+ # .args([" Hi " ])
44+ # .exec_output_bytes!()?
45+
46+ #Stdout.line!(" ${Str . inspect (cmd_output_bytes )}")?
47+
48+ Ok ({})
5049}
0 commit comments