pipe

 

 

 


Pipe output to two different commands

 

一共有兩方法

  • 方法1: process substitution ">(X)"
  • 方法2: named pipe

 

方法1: process substitution ">(X)"

tee >(command1) >(command2) | command3

">" 與 "(" 之間不可有空格

原理

The shell creates the pipe and passes a file name like /dev/fd/3 to the command.

The number is the file descriptor that the pipe is connected to.

應用例子: 有 md5 的 nc 傳檔

# Sender

time pv vda.qcow2 | tee >(md5sum > md5.txt) |  nc -w 2 127.0.0.1 6666

# Receiver

nc -v -l 6666 | tee >(md5sum > md5.txt) | pv > vda.qcow2

方法2: named pipe

基礎版

mkfifo pipe

cat pipe | (command 1) &

echo 'test' | tee pipe | (command 2)

 

多 command 進階版

tmp_dir=$(mktemp -d)
mkfifo "$tmp_dir/f1" "$tmp_dir/f2"
command1 <"$tmp_dir/f1" & pid1=$!
command2 <"$tmp_dir/f2" & pid2=$!
tee "$tmp_dir/f1" "$tmp_dir/f2" | command3
rm -rf "$tmp_dir"
wait $pid1 $pid2