仅在存在时附加到文件 [英] Append to file only if it exists
问题描述
我在SO上已经看到了几个答案,关于如何附加到文件(如果存在)以及如何创建不存在的新文件( echo"hello">> file.txt
)或覆盖一个文件(如果存在),如果不存在则创建一个文件( echo"hello"> file.txt
).
I've seen several answers on SO about how to append to a file if it exists and create a new file if it doesn't (echo "hello" >> file.txt
) or overwrite a file if it exists and create one if it doesn't (echo "hello" > file.txt
).
但是如何确保 echo"hello"
仅在文件已经存在的情况下起作用并追加到文件中,而在不存在的情况下引发错误?
But how do I make sure that echo "hello"
only works and appends to the file if it already exists and raises an error if it doesn't?
现在,我已经在使用 [-f file.txt]
检查文件了.我想知道是否有一种方法可以简单地使用 echo
.
Right now, I'm already checking for the file using [ -f file.txt ]
. I was wondering if there's a way in which I could simply use echo
.
推荐答案
假定文件不存在或者可读可写,则可以尝试打开文件以首先阅读以确定它是否存在,例如:>
Assuming the file is either nonexistent or both readable and writable, you can try to open it for reading first to determine whether it exists or not, e.g.:
command 3<file 3<&- >>file
在大多数情况下,可能会省略
3<&-
,因为程序意外地开始从文件描述符 3
读取而没有首先重定向它是意外的.
3<&-
may be omitted in most cases as it's unexpected for a program to start reading from file descriptor 3
without redirecting it first.
概念证明:
$ echo hello 3<file 3<&- >>file
bash: file: No such file or directory
$ ls file
ls: cannot access 'file': No such file or directory
$ touch file
$ echo hello 3<file 3<&- >>file
$ cat file
hello
$
之所以起作用,是因为从左到右处理了重定向,并且重定向错误导致命令的执行停止.因此,如果 file
不存在(或不可读),则 3< file
失败,则shell将输出一条错误消息并停止处理此命令.否则, 3<&-
关闭上一步中与 file
相关的描述符( 3
),>> file
重新打开 file
进行追加,并将标准输出重定向到该文件.
This works because redirections are processed from left to right, and a redirection error causes the execution of a command to halt. So if file
doesn't exist (or is not readable), 3<file
fails, the shell prints an error message and stops processing this command. Otherwise, 3<&-
closes the descriptor (3
) associated with file
in previous step, >>file
reopens file
for appending and redirects standard output to it.
这篇关于仅在存在时附加到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!