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.

3

1 Answer 1

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.

3
  • thanks that works for me! also nice using the slash at the end of the line and saving the line-break.
    – nath
    Commented Dec 7, 2017 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
    Commented Dec 7, 2017 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
    Commented Dec 7, 2017 at 22:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .