Search code examples
bashparameterspipexargs

pipe stdio to a function


Noob question!

I've got a function on the command line that takes parameters

sqr() { echo $(( $1 * $1 )) ; }

sqr 4 echos 16. fine.

Now I want to pipe an output to this function

echo 4 | sqr

I get " syntax error: operand expected (error token is "* ") " - clearly $1 is empty

I've tried using xargs with various options to pass the stdio to the function but I get "No such file or directory" errors. Am I missing something obvious?


Solution

  • One way could be using parameter expansion on $1 to have cat flush STDIN as fallback:

    $ sqr() { n=${1:-$(cat)}; echo $((n*n)); }
    
    $ sqr 6
    36
    
    $ echo 5 | sqr
    25
    
    $ echo 5 | sqr 6  # $1 takes precedence over STDIN
    36