“猫”和“猫<”的区别

roo*_*kie 74 io-redirection cat

我是通过一个教程和锯同时使用的工作cat myfile.txtcat < myfile.txt。这两个命令序列之间有区别吗?似乎都将文件的内容打印到 shell。

Tho*_*key 110

在第一种情况下,cat打开文件,在第二种情况下,shell 打开文件,将其作为cat标准输入传递。

从技术上讲,它们可能会产生不同的效果。例如,有可能拥有比cat程序更高(或更低)特权的 shell 实现。对于这种情况,一个可能无法打开文件,而另一个可能。

这不是通常的情况,但提到指出shell 和cat不是同一个程序。

  • 是的,例如你可以做`sudo cat myfile.txt`。但是如果您没有读取文件的权限,`sudo cat &lt; myfile.txt` 将无法工作。 (88认同)
  • 请注意,`ksh93` 内置了 `cat`(默认情况下不启用,除非你在 `$PATH` 的早期有 `/opt/ast/bin`)。 (2认同)
  • 某些程序的行为取决于它们是否获得文件名参数或标准输入。例如,当给定参数时,`wc` 将在计数之前打印文件名。 (2认同)

jll*_*gre 22

您的测试用例没有明显的明显差异。最明显的一个是如果myfile.txt当前目录中没有命名的文件或不允许您读取它,您会收到错误消息。

在前一种情况下,cat会抱怨,在后一种情况下,您的 shell 会清楚地显示哪个进程正在尝试打开文件,cat在前一种情况下,而在后一种情况下是shell。

$ cat myfile.txt
cat: myfile.txt: No such file or directory
$ cat < myfile.txt
ksh93: myfile.txt: cannot open [No such file or directory]
Run Code Online (Sandbox Code Playgroud)

在更一般的情况下,一个主要的区别是使用重定向不能用于打印多个文件的内容,这毕竟是cat(即cat enate)命令的最初目的。请注意,shell 无论如何都会尝试打开作为重定向输入传递的所有文件,但实际上只会将最后一个传递给,cat除非您使用zsh它的multios“zshism”。

$ echo one > one
$ echo two > two
$ cat one two # cat opens one, shows one, opens two, shows two
one
two
$ cat < one < two # sh opens one then opens two, cat shows stdin (two)
two
$ rm one two
$ echo one > one
$ cat one two # cat opens and shows one, fails to open two
one
cat: two: No such file or directory
$ cat < one < two # the shell opens one then opens two, fails and 
                  # displays an error message, cat gets nothing on stdin
                  # so shows nothing
ksh93: two: cannot open [No such file or directory]
Run Code Online (Sandbox Code Playgroud)

在标准系统上,shell 和cat在文件访问权限上没有区别,因此两者都会成功或失败。使用sudoto raisecat的特权将在行为上产生很大的不同,正如 Thomas Dickey 的回复和附加评论已经建议的那样。

  • 出于好奇,您是否真的自愿使用 `ksh`,如果是这样...... *为什么*? (5认同)
  • 正如@mikeserv 指出的 [其他地方](http://unix.stackexchange.com/questions/249804/#comment430086_249804),在以下情况下,`cat &lt; file1 &gt; file2` 与 `cat file1 &gt; file2` 具有非常不同的效果`file1` 不可读或不存在。(后一种形式会截断 `file2`;前者不会。) (5认同)
  • @mikeserv 本来是轻率的,不是很粗鲁,但足够公平,我想 (2认同)
  • @cat - 我没想到。无知并不是一件可耻的事情——它只是缺乏知识。如果您不明白为什么有人可能会选择使用 ksh93,那么我只能假设这是因为您从未使用过它。所以我建议你这样做。值得一试,可以肯定。相信我,当我告诉你时,与 `bash` 相比,`ksh93` 无疑是更好的 shell。几乎是*外壳。 (2认同)

Ham*_*bad 7

cat myfile.txt读取文件,myfile.txt然后将其打印到标准输出。

cat < myfile.txt这里cat没有提供任何要打开的文件,因此 - 就像许多 Unix 命令一样 - 从标准输入读取数据,标准输入file.txt由 shell从那里引导,并打印到标准输出。


sas*_*sha 6

@Thomas Dickey的回答很棒。

我只想添加一些关于阅读多个文件的情况的明显事实(与您的问题松散相关,但仍然如此):

  • cat <file1 <file2 <file3将只读取 file3,至少在 bash 中。(实际上,这取决于shell,但大多数shell会将每个指定的文件复制到stdin,这会导致最后一个生效。)
  • cat file1 file2 file3将按顺序读取所有指定的文件(实际上cat是单词concatenate 的缩写形式)。
  • cat file1 file2 file3 <file4 <file5 <file6 将只读取 file1、file2、file3(因为在传递文件名参数时 cat 会忽略 stdin)。
    • cat file1 file2 - file3 <file4 <file5 <file6 将读取 file1、file2、file6、file3(因为连字符强制 cat 不要忽略 stdin)。

以及关于错误。如果无法打开某些指定为参数的文件(没有<), cat 将跳过失败的文件(将相关消息输出到 stderr),但仍读取其他文件。如果无法打开至少一个指定为重定向的文件(使用<),shell 甚至不会启动 cat(即使对于 cat 实际未使用的重定向也会发生这种情况)。在这两种情况下,都会返回错误的退出代码。


归档时间:

查看次数:

17897 次

最近记录:

6 年 前