DEV Community

Arash
Arash

Posted on • Updated on

Executing bash script commands in a sub-shell to manage status code and output

Hello Communityđź‘‹,

This is my first post on Dev.to! For a long time, I thought it would be a good idea to share something that might help others, but perfectionism always got in the way. Each time I tried, I ended up with drafts and nothing more.

This time, I promised myself to start small, taking baby steps. I hope to keep this up, so here's my very small step into the blogging world.

I still believe in bash. I prefer to rely on bash wherever it's the best and most suitable option. I have code written 10 years ago that's still working. I created a complete deployment system 8 years ago in bash, which I believe is still in production. Over time, I've used some functions that have stuck with me like old friends. Today, I want to introduce one of them: run() function.
We've been friends for about 9-10 years now, and it's one of the best.

run() {
    { error=$($@ 2>&1 1>&$out); } {out}>&1
    local status=$?
    if [ $status -ne 0 ]; then
        messages+="$error\n"
        failed=true
        echo "$messages"
        exit 1
    fi
    return $status
}
Enter fullscreen mode Exit fullscreen mode

Link to gist.

The run() function in the given code executes a command in subshell, captures its output, logs any errors, and handles failure conditions. Here's a detailed breakdown of it's most important part of the function:

{ error=$($@ 2>&1 1>&$out); } {out}>&1
Enter fullscreen mode Exit fullscreen mode
  • { error=$($@ 2>&1 1>&$out); }: This captures the combined standard output and standard error of the command into the variable error from a subshell.
  • {out}>&1: This redirects the output back to standard output.

P.S Since I'm not a native English speaker, I used writing tools to help me with grammar.

Thank you.

Top comments (0)