Append to file only if it exists

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

    Just check:

    if [ -f file.txt ]; then
      echo "hello" >> file.txt
    else
      echo "No file.txt" >&2
      exit 1
    fi
    

    There's no way in bash to alter how >> works; it will always (try to) create a file if it doesn't already exist.

提交回复
热议问题