macoszsh

Is there a way to know if a command is being called at the beginning/end of a pipe?


It occurred to me that it would be very convenient if pbcopy and pbpaste could be combined into a single command that could infer the desired behavior based on usage.

I.e., if the command is called at the beginning of a pipe, it should paste the current clipboard into the pipe:

$ clipboard | sort -fh

$ clipboard > file1.txt

And if the command is called at the end of a pipe, the command with save the input to the clipboard:

$ echo $PATH | sed "s/:/\\n/g" | clipboard

So in general, is it possible to implement something like this?


Solution

  • It is possible to write a shell function that runs pbcopy if its stdin is not a terminal and pbpaste if its stdout is not a terminal.

    The code is as simple as:

    clipboard() {
      if ! [ -t 0 ]; then pbcopy; fi
      if ! [ -t 1 ]; then pbpaste; fi
    }
    

    I tested it on Bash and it works like a charm. I suppose that it also works in Zsh.

    It even works when it is inserted between two pipes (and this is the only situation when I think it is useful):

    $ echo "$PATH" | clipboard | sed "s/:/\\n/g"
    

    It puts on screen the paths in $PATH, one path per line (this is what the sed command line does) while in clipboard is the original content of $PATH.


    Read about shell functions, Bash conditional expressions and redirections.