0

I have a script using a pretty long pipe quite a lot of times. The middle of each pipe is the same command chain. Only the beginning and the end defers all the time it is used.

Different-command-1 |
 command A |
 command B |
 command C |
 diff-cmd-2

is there a way to call this commands as a function within the pipe? Like:

same-commands() {
    command A |
    command B |
    command C 
}

Different-command-1 | same-commands | diff-cmd-2

Different-command-3 | same-commands | diff-cmd-4

this in my case would save quite a lot of lines in my script, but I can not quite figure out how this could work.

nath
  • 5,694
  • related: https://unix.stackexchange.com/questions/383738/conditionally-include-a-pipe-stage-in-a-bash-script & https://unix.stackexchange.com/questions/38310/conditional-pipeline – ilkkachu Dec 07 '17 at 19:28
  • But as the function will just run the commands within it with the same stdin and stdout, you should be able to do func() { foo | bar; } and then use func in place of foo | bar – ilkkachu Dec 07 '17 at 19:31
  • @ilkkachu I do not quite understand what I'm doing wrong, I allways get syntax error near unexpected token (' maybe I should come up with a real MWE that could run... – nath Dec 07 '17 at 19:50

1 Answers1

5

The commands in a function run with the same stdin and stdout as the function itself, so we can just put a pipeline in a function, and the stick the function in another pipeline, as it if were any other command:

func() { 
    tr a x | 
    tr b x
}
echo abc | func | tr c x

This prints xxx.

ilkkachu
  • 138,973
  • thanks that works for me! also nice using the slash at the end of the line and saving the line-break. – nath Dec 07 '17 at 22:49
  • 1
    @nath, yeah, there's no special syntax for a pipeline in a function, the outer pipeline doesn't really need to know if one of the commands is a function instead of something else. – ilkkachu Dec 07 '17 at 22:50
  • 1
    @nath, and yes, backslashes are ugly :( Also, with foo() { ... }, you don't want to have a backslash before the closing }, the syntax requires a newline or a semicolon there. – ilkkachu Dec 07 '17 at 22:52