foo() { if [ -t 0 ]; then echo "Called normally" echo "Received arg: $1" else echo.green "Called from a pipeline" while IFS= read -r line; do echo "Processing piped input: $line" done fi}export -f foomain() { echo "Calling foo() normally" foo "bar" echo "--------------------------------------------------------------------------------" echo "Calling foo() from a pipeline" echo "bar" | foo}main "${@}" || exit 1
Output:
Calling foo() normallyCalled normallyReceived arg: bar--------------------------------------------------------------------------------Calling foo() from a pipelineCalled from a pipelineProcessing piped input: barreal 0m0.016suser 0m0.013ssys 0m0.004s
Compress piped input with JQ
# shellcheck disable=SC2120bar(){ if [ -t 0 ]; then echo "BAR Called normally: $*" else echo "BAR Called from a pipeline" while IFS= read -r line; do echo.bold "BAR Processing piped input: $line" sleep 2 done fi}foo() { if [ -t 0 ]; then echo "${*:?}" | jq -c | bar else jq -c | bar fi}export -f foomain() { echo.green "$(date.now)" echo.jsonl | jq | foo echo.green "$(date.now)" foo '{"hi":"there"}'}main "${@}" || exit 1
Output:
2023-12-14T21-17-51PSTBAR Called from a pipelineBAR Processing piped input: {"title":"title-val-1","note":"note-val-1"}BAR Processing piped input: {"title":"title-val-2","note":"note-val-2"}BAR Processing piped input: {"title":"title-val-3","note":"note-val-3"}2023-12-14T21-17-57PSTBAR Called from a pipelineBAR Processing piped input: {"hi":"there"}