jse*_*ksn 34 bash io-redirection
我知道>(右 V 形)用于将程序的 STDOUT 重定向到文件,因为echo 'polo' > marco.txt将创建一个文本文件作为内容调用marco.txt,polo而不是将其写入终端输出。我也明白和之间的差|(管道),其用于在管的右左侧的管从所述第一命令重定向STDOUT于第二命令的STDIN,如在echo 'Hello world' | less以显示Hello world在less看法。
我真的不明白这是如何<工作的。我试过了marco.txt < echo 'polo',bash 给了我一个错误:-bash: echo: No such file or directory. 有人可以解释它是如何工作的以及我为什么要使用它吗?
Arg*_*uts 24
运算符 < 最常用于重定向文件内容。例如
grep "something" < /path/to/input.file > /path/to/output.file
Run Code Online (Sandbox Code Playgroud)
这将 grep input.file 的内容,将包含“某物”的行输出到 output.file
它不是 > 运算符的完整“逆”运算符,但它在文件方面的意义有限。
对于一个非常好的和简短的描述,以及 < 的其他应用程序,请参阅 io 重定向
更新:在此处的评论中回答您的问题是如何使用 < 操作符使用 bash 处理文件描述符:
您可以将 stdin (0)、stdout (1) 和 stderr (2) 之外的其他输入和/或输出添加到 bash 环境中,这有时比不断切换重定向输出的位置更方便。bash 中 3 个“std”输入/输出旁边的 () 中的 # 是它们的“文件描述符”,尽管它们在 bash 中很少以这种方式被引用 - 在 C 中更常见,但即使如此,也定义了常量从这些数字中抽象出来的东西,例如 STDOUT_FILENO 在 unistd.h 或 stdlib.h 中定义为 1 ...
假设您有一个脚本,该脚本已经在使用 stdin 和 stdout 与用户终端进行交互。然后,您可以打开其他文件进行读取、写入或两者兼而有之,而不会影响 stdin / stdout 流。这是一个简单的例子;与上面 tldp.org 链接中的材料类型基本相同。
#!/bin/bash -
#open a file for reading, assign it FD 3
exec 3</path/to/input.file
#open another file for writing, assign it FD 4
exec 4>/path/to/output.file
#and a third, for reading and writing, with FD 6 (it's not recommended to use FD 5)
exec 6<>/path/to/inputoutput.file
#Now we can read stuff in from 3 places - FD 0 - stdin; FD 3; input.file and FD 6, inputoutput.file
# and write to 4 streams - stdout, FD 1, stderr, FD 2, output.file, FD 4 and inputoutput.file, FD 6
# search for "something" in file 3 and put the number found in file 4
grep -c "something" <&3 >&4
# count the number of times "thisword" is in file 6, and append that number to file 6
grep -c "thisword" <&6 >>&6
# redirect stderr to file 3 for rest of script
exec 2>>&3
#close the files
3<&-
4<&-
6<&-
# also - there was no use of cat in this example. I'm now a UUOC convert.
Run Code Online (Sandbox Code Playgroud)
我希望它现在更有意义 - 你真的必须稍微玩弄它才能让它下沉。只要记住 POSIX 的口头禅——一切都是一个文件。所以当人们说 < 真的只适用于文件时,它并不是限制 Linux / Unix 中的一个问题;如果某些内容不是文件,您可以轻松地使其外观和行为像一个文件。
它将文件 after 重定向<到程序的 stdin before <。
foo < bar
Run Code Online (Sandbox Code Playgroud)
将foo使用该文件bar作为其标准输入运行程序。