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:
bashmy_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" }
-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.bashmy_function "This is a single line"
bashecho -e "Line 1\nLine 2" | my_function
or
bashmy_function <<EOF Line 1 Line 2 EOF
Vibe can make mistakes. Check answers. Learn more