首页 > `cat <> file`是怎么处理的

`cat <> file`是怎么处理的

假如有一个file文件

Hello, World!

然后再bash下面执行

cat <> file

输出的结果是:

Hello, World!

请问这中间到底发生了什么?


Update

想了一下 cat <> file相当于cat 0<> file。之后在网上找到了如下信息:

Use program <> file to open file for both reading and writing.

I/O Redirection

[j]<>filename
# Open file "filename" for reading and writing,
#+ and assign file descriptor "j" to it.
# If "filename" does not exist, create it.
# If file descriptor "j" is not specified, default to fd 0, stdin.
#
# An application of this is writing at a specified place in a file.

echo 1234567890 > File    # Write string to "File".
exec 3<> File             # Open "File" and assign fd 3 to it.
read -n 4 <&3             # Read only 4 characters.
echo -n . >&3             # Write a decimal point there.
exec 3>&-                 # Close fd 3.
cat File                  # ==> 1234.67890

3.6 Redirections

The redirection operator
[n]<>word
causes the file whose name is the expansion of word to be opened for both reading and writing on file descriptor n, or on file descriptor 0 if n is not specified. If the file does not exist, it is created.


正如题主自己所说,cat <> file 相当于 cat 0<> file,即以读写方式打开 file,并且把 fd 设为 0。

因为 0 是 stdin,所以只是写 cat <> file 并没有什么实际意义,和 cat < file 在表现上没什么区别,只是多了些副作用,包括需要拥有 file 的写权限,如果不存在 file 会自动创建一个新的空文件等。

【热门文章】
【热门文章】