we all know how to pipe to shell scripts and installed programs like grep,awk ... but what about a sourced function in .bashrc or .zshrc ?

this is a test function :

function fff(){
    echo "$@"

and this is a test command :

$ echo "hello world" | fff

and it does not work


Your function expects command line arguments, not data over the standard input stream (which it gets when you pipe to it).

What you could possibly do is to test whether the function was given any command line arguments, and if not, output the standard input stream instead:

fff () {
    if [ "$#" -gt 0 ]; then
       echo "$@"


$ echo "hi there" | fff
hi there

An alternative solution would be to use a command substitution with you original function definition:

fff "$( echo "hi there" )"

This would set $@ in the function to the single string hi there. This would be a perfectly valid solution if the piped data is a single string or a short line of text. For processing larger quantities of data, consider doing so in the usual line-by-line manner (possibly using awk) in place of the call to cat in the above function definition, and read the data off a pipe as in the test above.

  • ultimately the function needs to capture the piped data as a variable for other purposes – Neo Mosaid Jan 19 at 10:34
  • @NeoMosaid See updated answer. – Kusalananda Jan 19 at 10:38
  • thanks , aa=$( cat ) ; captured the stdin data, and it's just what I needed – Neo Mosaid Jan 19 at 10:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.