title: Bash: test if a variable exists within another variable?
body: <p>I have two variables, both are a list of filenames that have been moved by a script.</p>
  <p><strong>Variable 1</strong>:
  Generated by a 'read' loop of a larger variable. At any given moment it only contains one filename.</p>
  <blockquote>
  <p>var1 = pic1.jpg</p>
  <p>var1 = pic2 duplicate.jpg</p>
  <p>var1 = pic3(dup).jpg</p>
  <p>var1 = pic4.jpg</p>
  <p>var1 = subfolder/subfolder picture.png</p>
  </blockquote>
  <p>As shown above, the filenames can contain spaces, but do not always.</p>
  <p><strong>Variable 2</strong>: A string containing a list of files, each filename being separated by a <code>\n</code> newline character.</p>
  <blockquote>
  <p>var2 = pic1.jpg <code>\n</code> pic2 duplicate.jpg <code>\n</code> pic3(dup).jpg <code>\n</code> pic4.jpg</p>
  </blockquote>
  <p>I am attempting to test if the contents of <strong>var1</strong> can be found in <strong>var2</strong>:</p>
  <pre><code>    listcontains() {
          for list_item in $1; do
              # Does $list_item exist in $2?
              if [[ &quot;$list_item&quot; =~ &quot;$2&quot; ]]; then
                  return 0
              else
                  return &quot;1&quot;
              fi
          done
  
      }
  
      # Call function to see if var1 is in var2
      if listcontains &quot;$var1&quot; &quot;$var2&quot;
         then
             # var1 is in var2; do stuff...
         else
             # Do different stuff...
     fi
  </code></pre>
  <p>This logic is clearly wrong, or the syntax is wrong, as it always returns a non-match at the moment:</p>
  <pre><code>does pic2 exist in pic2 duplicate.jpg
  pic2.jpg
  pic3(dup).jpg
  pic3.jpg?
  no
  
  does pic3(dup).jpg exist in pic2 duplicate.jpg
  pic2.jpg
  pic3(dup).jpg
  pic3.jpg?
  no
  </code></pre>
  <p>I'm still learning bash, so if anybody could help me then it would be massively appreciated.</p>