title: Nested for loop to enter and exit multiple directories Bash script
body: <p>As an example, I have 7 directories each containing 4 files. The 4 files follow the following naming convention name_S#_L001_R1_001.fastq.gz. The sed command is to partially keep the unique file name.</p>
  
  <p>I have a nested for loop in order to enter a directory and perform a command, exit the directory and proceed to the next directory. Everything seems to be working beautifully, however the code gets stuck on the last directory looping 4 times.   </p>
  
  <pre><code>for f in /completepath/*
  do
      [ -d $f ] &amp;&amp; cd "$f" &amp;&amp; echo Entering into $f
      for y in `ls *.fastq.gz | sed 's/_L00[1234]_R1_001.fastq.gz//g' | sort -u`
      do
          echo ${y}
      done
  done
  </code></pre>
  
  <p>Example output- </p>
  
  <pre><code>Entering into /completepath/m_i_cast_avpv_1
  iavpvcast1_S6
  Entering into /completepath/m_i_cast_avpv_2
  iavpvcast2_S6
  Entering into /completepath/m_i_int_avpv_1
  iavpvint1_S5
  Entering into /completepath/m_i_int_avpv_2
  iavpvint2_S5
  Entering into /completepath/m_p_cast_avpv_1
  pavpvcast1_S8
  Entering into /completepathd/m_p_int_avpv_1
  pavpvint1_S7
  Entering into /completepath/m_p_int_avpv_2
  pavpvint2_S7
  pavpvint2_S7
  pavpvint2_S7
  pavpvint2_S7
  </code></pre>
  
  <p>Any recommendations of how to correctly exit the inner loop? </p>