Skip to main content

Unix 杂记:cat(1)

  cat 是 con__cat__enate 的缩写。第一版手册对 cat 的介绍是 concatenate and print1:16 2:1597,今天的多数版本则径作 catenate and print。Kernighan & Pike 说 cat 源自 catenate,又补充道:“Catenate” is a slightly obscure synonym for “concatenate”3:15。Hahn 则直接说 cat 代表 catenate 而非 concatenate4:344。拉丁语 con- (< cum) 有时确无实义,但这里可否略去还需研究。

  cat 的一般形式为:

cat file1  filen\verb|cat |\textit{file}_1\verb| |\cdots\verb| |\textit{file}_n

其中 n1n\geq1。若 n=1n=1,concatenate 功能退化为 print 功能。

  cat 不带参数时特殊,从__标准输入__读取内容。所谓特殊并非就标准输入本身而言——Unix 下的标准输入本就是文件。特殊之处在于标准输入只是__一个__文件。换言之,此时必然退化。反之,只要是单个文件,即使不是标准输入,也可引至标准输入。因此:

cat file  cat <file\verb|cat |\textit{file}\verb| |\equiv\verb| cat <|\textit{file}

这也显示出退化情形的特殊性。

  由于左边的写法更简洁,不带参数的 cat 不常用(注意:<file\verb|<|\textit{file} 并非参数)。Pike & Kernighan 指出,一般的 cmd  <file\textit{cmd}\verb| |\cdots\verb| <|\textit{file} 也有为 cat file | cmd \verb|cat |\textit{file}\verb/ | /\textit{cmd}\verb| |\cdots 所取代的趋势2:1598。区别在于打开文件(这里仅指标准 IO 以外的文件)的任务是由 shell 完成还是由 cat 完成。

  此外,Hahn 提到不带参数的 cat 可用于在 shell 里编写或续写文本:4:343

cat >filecat >>file\begin{array}{l} \verb|cat >|\textit{file}\\ \verb|cat >>|\textit{file} \end{array}

这种用法恐怕也不常见。

  cat 原本不带任何选项。今天的 cat 可有不少选项(Plan 9、Inferno 除外)。以 GNU coreutils 为例:(略去些次要的)

-b, --number-nonblank    number nonempty output lines, overrides -n
-E, --show-ends display $ at end of each line
-n, --number number all output lines
-s, --squeeze-blank suppress repeated empty output lines
-T, --show-tabs display TAB characters as ^I
-v, --show-nonprinting use ^ and M- notation, except for LFD and TAB

针对此类现象,Pike & Kernighan 撰文提出批评2。该文已是 Unix 哲学的经典,这里不再引述。激进网站 cat-v.org 便得名于此(相关页面)。


【下方参考文献后的「返回」功能基本无效,请无视之。】

Footnotes

  1. M. D. McIlroy, A Research UNIX Reader, 1987.

  2. R. Pike & B. W. Kernighan, ‘Program Design in the UNIX Environment’, AT&T Bell Laboratories Technical Journal 63, 1984. 2 3

  3. B. W. Kernighan & R. Pike, The UNIX Programming Environment, Prentice-Hall, 1984.

  4. H. Hahn, 『Unix & Linux 大学教程』, 张杰良译, 清华大学出版社, 2010. 2