2

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.

3
+50

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.

0

Please don't thumb up this answer but Stephen's one which I marked correct. This is but a variation easier for me to read.


If the content of the template file should only be appended to the end file if none of it is already present in the end file, you can use grep:

cat <<-"EOF1" > myPath/myTemplate
    content...
EOF1

if ! grep -F -q -f myPath/myFile myPath/myTemplate; then
    cat myPath/myTemplate >> myPath/myFile
fi

The grep command searches myPath/endFile.sh for any fixed string (-F) contained in myPath/myTemplate, 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 then block of the if-then block will only be executed if grep doesn’t match anything in the end file.

Appendix - exit codes:

When a process exits, it returns an exit code, which is a small integer. By convention, an exit code of 0 indicates success, non-zero indicates failure or an error:

  • grep returns 0 when it finds a match, and 1 if it doesn’t.

  • if uses its argument’s exit code to decide what to do; if 0, process the then block, otherwise the else block (if any).

  • A punctuation (!) flips that; The then block only runs if grep doesn’t match anything (or encounters an error).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.