管道的正式定义表明左侧文件的STDOUT将立即通过管道传送到正确文件的STDIN.我有两个文件,hello.txt和human.txt. cat hello.txt返回Hello并cat human.txt返回I am human.如果我这样做cat hello.txt | cat human.txt,不应该返回Hello I am human吗?相反,我正在看command not found.我是shell脚本的新手.有人可以解释一下吗?
背景:管道在左侧安排输出命令(即写入FD 1,stdout的内容)作为输入传递给右侧的命令(在FD 0,stdin上).它通过使用"管道"或FIFO连接进程并同时执行它来完成此操作; 尝试从FIFO读取将等到另一个进程写入某些内容,并且尝试写入FIFO将等待另一个进程准备好读取.
cat hello.txt | cat human.txt
Run Code Online (Sandbox Code Playgroud)
...将内容hello.txt输入到标准输入中cat human.txt,但cat human.txt不是从标准输入中读取 ; 相反,它的命令行参数指向它只读human.txt.
因此,stdin上的内容cat human.txt被忽略并且从不读取,并且cat hello.txt在cat human.txt退出时接收SIGPIPE ,并且此后也退出.
cat hello.txt | cat - human.txt
Run Code Online (Sandbox Code Playgroud)
...相比之下,第二次cat从stdin读取(你也可以用来/dev/stdin代替-许多操作系统,包括Linux),然后从文件中读取.