Append to file only if it exists

后端 未结 4 1209
故里飘歌
故里飘歌 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:43

    I think a simple if as proposed in the other answers would be best. However, here are some more exotic solutions:

    Using dd

    dd can do the check and redirection in one step

    echo hello | dd conv=nocreat of=file.txt
    

    Note that dd prints statistics to stderr. You can silence them by appending 2> /dev/null but then the warning file does not exist goes missing too.

    Using a custom Function

    When you do these kind of redirections very often, then a reusable function would be appropriate. Some examples:

    Run echo and redirect only if the file exists. Otherwise, raise the syntax error -bash: $(...): ambiguous redirect.

    ifExists() { [ -f "$1" ] && printf %s "$1"; } 
    echo hello >> "$(ifExists file.txt)"
    

    Always run echo, but print a warning and discard the output if the file does not exist.

    ifExists() {
      if [ -f "$1" ]; then
        printf %s "$1"
      else
        echo "File $1 does not exist. Discarding output." >&2
        printf /dev/null
      fi
    } 
    echo hello >> "$(ifExists file.txt)"
    

    Please note that ifExists cannot handle all file names. If you deal with very unusual filenames ending with newlines, then the subshell $( ...) will remove those trailing newlines and the resulting file will be different from the one specified. To solve this problem you have to use a pipe.

    Always run echo, but print a warning and discard the output if the file does not exist.

    appendIfExists() {
      if [ -f "$1" ]; then
        cat >> "$1"
      else
        echo "File $1 does not exist. Discarding output." >&2
        return 1
      fi
    } 
    echo hello | appendIfExists file.txt
    

提交回复
热议问题