Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic Analog to Ruby's `Object#tap` for Unix command Pipelines?

Is there an idiomatic analog to Ruby's Object#tap for Unix command pipelines?

Use case: within a pipeline I want to execute a command for its side effects but return the input implicitly so as to not break the chaining of the pipeline. For example:

echo { 1, 2, 3 } |
  tr ' ' '\n' |
  sort |
  tap 'xargs echo' | # arbitrary code, but implicitly return the input
  uniq

I'm coming from Ruby, where I would do this:

[ 1, 2, 3 ].
  sort.
  tap { |x| puts x }.
  uniq
like image 671
pje Avatar asked Sep 22 '12 16:09

pje


1 Answers

The tee command is similar; it writes its input to standard output as well as one or more files. If that file is a process substitution, you get the same effect, I believe.

echo 1 2 3 | tr ' ' '\n' | sort | tee >( **code** ) | uniq

The code in the process substitution would read from its standard input, which should be the same thing that the call to uniq ends up seeing.

like image 88
chepner Avatar answered Nov 15 '22 02:11

chepner