How to make a Bash function either read (multiple lines stdin) or (single line first argument)?
May 30, 8:52am

In Bash, you can create a function that reads either from multiple lines of stdin or from a single line passed as the first argument by checking if stdin is being piped or if an argument is provided. Here’s a clean and idiomatic way to do it:

Solution

bash
my_function() {
    if [ -t 0 ]; then
        # No stdin (not piped), so read from the first argument
        if [ -z "$1" ]; then
            echo "Error: No input provided." >&2
            return 1
        fi
        input="$1"
    else
        # Read all lines from stdin
        input=$(cat)
    fi

    # Process the input (example: print it)
    echo "Input received:"
    echo "$input"
}

How It Works

  • -t 0: Checks if stdin is a terminal (i.e., not piped). If true, the function reads from the first argument.
  • -z "$1": Checks if the first argument is empty.
  • $(cat): Reads all lines from stdin if input is piped.

Usage Examples

1. Pass input as an argument:

bash
my_function "This is a single line"

2. Pipe input from stdin (multiple lines):

bash
echo -e "Line 1\nLine 2" | my_function

or

bash
my_function <<EOF
Line 1
Line 2
EOF

May 30, 8:52am

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

Vibe can make mistakes. Check answers. Learn more