Using `tee` for Commands – Shell Scripting with IO Redirection

coreutilsio-redirectionshell-scriptteexsel

tee can redirect the piped standard input into the standard output and file.

echo Hello, World! | tee greeting.txt

The command above would display the greeting on the terminal screen and save it in the contents of greeting.txt file, creating the file if there's none by that name.

There's also -a switch for tee to append to the existing file instead of overwriting.


Is there a convenient way to redirect the piped input to the command and standard output instead of file?

I am trying to create a wrapper script for buku to copy to primary selection the URL of the bookmark specified by its index number.

# bukuc:
#!/bin/sh
url=$(buku -f 1 -p $1 | cut -f 2) # NUMBER : URL
echo $url # DISPLAY
echo $url | xsel # PRIMARY SELECTION

Here I use echo two times, first for displaying on the terminal, and then saving in the primary selection (clipboard).

I imagine something of echo $url | teeC xsel or a shortcut to display the output before passing to the next command (chaining commands), what would allow me to chain the whole command in one line without the need to save the result in a variable as follows:

buku -f 1 -p $1 | cut -f 2 | teeC xsel    

I can also use it with urlview to view, select, and open with the $BROWSER as follows:

bukuc 10-20 | urlview

Best Answer

It's straightforward in shells that support process substitution, e.g. bash

$ echo foo | tee >(xsel)
foo
$ xsel -o
foo

Otherwise, you could use a FIFO (although it lacks convenience)

$ mkfifo _myfifo
$ xsel < _myfifo &
$ echo bar | tee _myfifo
bar
$ xsel -o
bar
[1] + Done                       xsel 0<_myfifo
$ 
Related Question