Search code examples
shellprocessexeccrystal-lang

How to get the output of Process.exec in crystal-lang?


I need to get the output of Process.exec (not Process.run) as a string in crystal. Can this be done?

I've tried

Process.exec base, args

But it only puts it to the console. I'd like to put it in a variable.


Solution

  • As already clarified in comments, you can't capture output of a process executed using Process.exec, but there are ways to execute a process and capture it's output.

    The most straightforward one - backticks:

    output = `echo "Hello world"`
    

    In more complex scenarios (e.g. you need to capture standard output and standard error output separately, need to get also it's status, or to have greater control over it's execution) you can use something like this:

    stdout = IO::Memory.new
    process = Process.new("echo", ["Hello world"], output: stdout)
    status = process.wait
    output = stdout.to_s
    

    or

    stdout = IO::Memory.new
    status = Process.run("echo", ["Hello world"], output: stdout)
    output = stdout.to_s