“echo temp.txt” 中的“”到底是什么意思?

“echo  temp.txt” 中的“”到底是什么意思?

不存在的文件

$ ls file_not_exists.txt
ls: cannot access file_not_exists.txt: No such file or directory
$ echo <> file_not_exists.txt

$ ls file_not_exists.txt 
file_not_exists.txt
$ cat file_not_exists.txt
$

包含内容的文件

$ cat temp.txt 
asdf
$ echo temp.txt 
temp.txt
$ echo <> temp.txt 

$ cat temp.txt 
asdf 

如果文件不存在,echo <> file_not_exists.txt将创建一个新文件。所以我认为>可以工作(将空输出重定向到新创建的文件中)。但如果文件中有内容(例如temp.txt),为什么不将其清空echo <> temp.txt

答案1

来自高级 Bash 脚本指南

[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
  #  Random access, by golly.

所以,

echo <> temp.txt

如果不存在则创建temp.txt,并打印一个空行。就是这样。它相当于:

touch temp.txt && echo

笔记,最多程序不会期望 STDIN 文件描述符(0)处于打开状态以供写入,因此最多情况下,以下内容大致相同:

command <> file
command 0<> file
touch file && command < file

从那时起最多程序不会期望 STDOUT 被打开以供读取,以下通常大致等效:

command 1<> file
command > file

对于 STDERR:

command 2<> file
command &2> file

答案2

echo <> temp.txt导致文件temp.txt被打开以供读取在文件描述符0(stdin)上写入。

man bash

打开文件描述符进行读写重定向运算符

          [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.

相关内容