Course contentsShow
← Linux
Lesson 124 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Standard Stream Redirection Patterns

Orchestrate complex I/O pipelines between functions and external processes.

In this lesson, you will learn how to orchestrate data flow between functions and external processes by strategically redirecting standard input, output, and error streams.

The Mechanics of Stream Orchestration

At this stage in your scripting journey, you know that every process starts with three default channels: stdin (0), stdout (1), and stderr (2). Orchestrating complex pipelines isn't just about chaining commands with pipes (|); it is about managing where these streams originate and terminate when functions and external binaries interact.

When you encapsulate logic inside a function, that function inherits the environment of your shell. By applying redirection at the point of the function call, you can create modular "processing units" that don't need to know about files or external logging mechanisms—they simply receive input and emit output.

Practical Implementation

Consider a scenario where you have a function designed to process data. Instead of hardcoding a file path, you can use stream redirection to feed it data from a process substitution or a specific file descriptor:

# A simple function that expects input on stdin
process_data() {
    while read -r line; do
        echo "Processing: $line"
    done
}

# Orchestrating an external process and a function
# 1. Capture external errors to a specific log
# 2. Redirect output into our function
{
    cat data.txt | process_data
} 2> error.log

In this pattern, the function process_data remains "pure"—it doesn't care if the data came from cat, a network socket, or a process substitution. By wrapping the pipeline in curly braces {}, you group the commands, allowing you to redirect the stderr of the entire block to error.log while letting the stdout flow through your pipeline unimpeded.

This approach prevents your main script logic from becoming cluttered with file-handling code. You isolate the I/O configuration to the boundaries of the execution, keeping your functions reusable across different environments. Whether you are piping the output of a grep process into a function or capturing the combined stdout and stderr of a command into a variable for later parsing, you are effectively acting as the "traffic controller" for your script's data.

Key Takeaway: Redirect streams at the boundary of your functions and command groups to decouple your processing logic from your file I/O operations.