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
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<&-
may be omitted in most cases as it's unexpected for a program to start reading from file descriptor 3
without redirecting it first.
Proof of concept:
$ echo hello 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
$ cat file
hello
$
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
3<&-
closes the descriptor (3
) associated with file
in previous step, >>file
reopens file
for appending and redirects standard output to it.