roo*_*kie 74 io-redirection cat
我是通过一个教程和锯同时使用的工作cat myfile.txt和cat < myfile.txt。这两个命令序列之间有区别吗?似乎都将文件的内容打印到 shell。
Tho*_*key 110
在第一种情况下,cat打开文件,在第二种情况下,shell 打开文件,将其作为cat标准输入传递。
从技术上讲,它们可能会产生不同的效果。例如,有可能拥有比cat程序更高(或更低)特权的 shell 实现。对于这种情况,一个可能无法打开文件,而另一个可能。
这不是通常的情况,但提到指出shell 和cat不是同一个程序。
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 的回复和附加评论已经建议的那样。
cat myfile.txt读取文件,myfile.txt然后将其打印到标准输出。
cat < myfile.txt这里cat没有提供任何要打开的文件,因此 - 就像许多 Unix 命令一样 - 从标准输入读取数据,标准输入file.txt由 shell从那里引导,并打印到标准输出。
@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 次 |
| 最近记录: |