Operations 5 min read

How to Build a Robust Shell Function for Capturing Command Output and Errors

This guide explains how to capture command output and error messages in shell scripts, demonstrates basic output capture with $(), shows conditional handling using if statements, and provides a reusable run_command function—both simple and enhanced versions—to improve script robustness and maintainability.

Ops Development & AI Practice
Ops Development & AI Practice
Ops Development & AI Practice
How to Build a Robust Shell Function for Capturing Command Output and Errors

In shell scripting, capturing a command's output and error information is a common requirement for building robust and flexible scripts. This article walks through creating a generic execution function that captures both output and errors, and handles the command's exit status.

1. Basic Command Output Capture

You can capture a command's output in a shell script using backticks (``) or the $( ) syntax. For example:

output=$(ls /optdd 2>&1)
echo $output

This attempts to list the /optdd directory and assigns any output, including error messages, to the variable output. However, this approach does not provide a clear error‑handling mechanism when the command fails.

2. Using if to Process the Command’s Return Status

By combining an if statement, you can execute different actions based on the command’s exit status:

if ! res=$(ls /optdd 2>&1); then
    echo "error: $res"
fi

If ls /optdd fails, the if condition evaluates to true and the error message is printed, allowing the script to handle success and failure more explicitly.

3. Encapsulating the Logic into a Reusable Function

To improve reusability and maintainability, the above logic can be wrapped in a function that executes a command, captures its output and error, and returns an appropriate status:

run_command() {
    local cmd="$1"
    local res
    if ! res=$($cmd 2>&1); then
        echo "error: $res"
        return 1
    else
        echo "output: $res"
        return 0
    fi
}
# Example usage
run_command "ls /optdd"

The function receives the command as its first argument ( $1), runs it, captures both standard output and error, prints a message based on the exit status, and returns a corresponding status code.

4. Enhancing the Function for Greater Flexibility

An enhanced version can accept additional arguments, allowing more complex command invocations and providing detailed success/failure messages:

run_command() {
    local cmd="$1"
    shift
    local res
    if ! res=$($cmd "$@" 2>&1); then
        echo "Command failed: $cmd $@"
        echo "Error: $res"
        return 1
    else
        echo "Command succeeded: $cmd $@"
        echo "Output: $res"
        return 0
    fi
}
# Example usage
run_command ls -l /optdd

This version accepts multiple parameters, executes the composed command, and clearly reports both the command outcome and its output, making the script more powerful and generic.

Conclusion

By encapsulating command execution into a function, shell scripts become more robust and maintainable. Whether capturing output and errors or branching logic based on exit status, this approach provides greater flexibility and control for script authors.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Error HandlingShell scriptingbash functioncommand outputscript robustness
Ops Development & AI Practice
Written by

Ops Development & AI Practice

DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.