title: Add a line to a file section unless it exists
body: <p>I have a file that looks like this:</p>
  
  <pre><code>...
  %ldirs
  (list of line-separated directories)
  ...
  </code></pre>
  
  <p>With a shell script, I need to add a directory to the list in that file, but only if that directory is not already in the list. Here's the catch: The directory in question must come from a variable $SOME_PATH.</p>
  
  <p>I thought about using the patch utility, but to do that I would have to generate the patch file dynamically to add "+$SOME_PATH". The other problem is that I do not know the "after context" or the line number of "%ldirs", so generating the patch file is problematic.</p>
  
  <p>Is there another option?</p>
  
  <p>Tweaked answer - Thanks to Rob:</p>
  
  <pre><code>line=$(grep "$SOME_PATH" /path/to/file)
  if [ $? -eq 1 ]
      then
      sed -i "/%ldirs/ a\\$SOME_PATH" /path/to/file
  fi
  </code></pre>
  
  <p>Final answer - Thanks to tripleee:</p>
  
  <pre><code>fgrep -xq "$SOME_PATH" /path/to/file || sed -i "/%ldirs/ a\\$SOME_PATH" /path/to/file
  </code></pre>