Bash – Append Heredocument Content to File If Not Exists

bashcontrol flowhere-documentio-redirection

I have a file to which I want to append some content (including the first, second and third empty spaces visible in my code below):


### I am text 1

### I am text 2

(The actual text I append is way longer than these 5 lines).

To simply append content to a file, I do:

cat <<-"EOF" >> myPath/myFile
    content...
EOF

But how could I ensure that the heredocument would append the content only if the content doesn't already exist in a file, and that otherwise the operation would be aborterd?

If only part of the block content already exists in the file, the entire operation should also be aborted.

Best Answer

If the here document should only be added if none of it is present, you can use grep:

cat <<-"EOF1" > myPath/myFile.append
    content...
EOF1
if ! grep -F -q -f myPath/myFile{.append,}; then
    cat myPath/myFile.append >> myPath/myFile
fi

To understand this, consider the following.

  • grep -F -q -f myPath/myFile{.append,} is expanded by the shell to grep -F -q -f myPath/myFile.append myPath/myFile.

  • The grep command searches myPath/myFile (the file to which the text should be added if necessary) for any fixed string (-F) contained in myPath/myFile.append (the file containing the text to add), reading one pattern per line (-f), and indicates whether it finds any only by its exit code, with no output (-q).

  • The result is then negated !, so that the if block’s then part is only run if grep doesn’t find anything.

Related Question