Append to file only if it exists

后端 未结 4 1201
故里飘歌
故里飘歌 2021-01-18 19:05

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

4条回答
  •  没有蜡笔的小新
    2021-01-18 19:24

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

提交回复
热议问题