bash 重定向
Bash重定向:基础知识 (Bash Redirection: The Basics)
A bash script is commonly a set of commands. There are three standard file descriptors of any command:
bash脚本通常是一组命令。 任何命令都有三个标准文件描述符:
- 0 → stdin 0→标准输入
- 1 → stdout 1→标准输出
- 2 → stderr 2→标准错误
There are two commonly used redirection operators:
有两种常用的重定向运算符:
> output (This is the default operator for fd 1)
>输出(这是fd 1的默认运算符)
< input (This is the default operator for fd 0)
<输入(这是fd 0的默认运算符)
输出重定向 (Output Redirection)
The most basic example of redirecting the output of a command to a file is:
将命令输出重定向到文件的最基本示例是:
echo "hello world" 1> foo.txt
This redirects the output of the echo command to a file called foo.txt
. Since 1 is the default file descriptor for the >
operator, it can be omitted. Hence the following is a valid bash command.
这会将echo命令的输出重定向到名为foo.txt
的文件。 由于1是>
运算符的默认文件描述符,因此可以省略。 因此,以下是有效的bash命令。
echo “hello world” > foo.txt
echo “hello world” > foo.txt
无障碍和强制重定向 (No Clobber and Forced Redirection)
If the noclobber
option to the set
builtin has been enabled, the output redirection will fail if the file exists and is a regular file.
如果noclobber
选项的set
内建已启用,如果该文件存在并且是一个普通文件的输出重定向将失败。
The forced redirection operator >|
will redirect the output to the file even if the noclobber
option is set.
强制重定向运算符 >|
即使设置了noclobber
选项,也会将输出重定向到文件。
输入重定向 (Input Redirection)
Likewise, the most canonical example of the <
operator is the following command:
同样, <
运算符的最典型示例是以下命令:
read input < foo.txt && echo "${input}"
为文件分配文件描述符 (Assigning file descriptors to files)
Turns out there’s more that can be done with file descriptors in bash than just use it to redirect the input or output of commands.
事实证明,使用bash中的文件描述符可以完成的工作不仅仅用于重定向命令的输入或输出。
In particula