title: Bash script to delete files in a directory if there are more than 5
body: <p>This is a backup script that copies files from one directory to another.  I use a <code>for</code> loop to check if there are more than five files.  If there are, the loop should delete the oldest entries first.</p>
  
  <p>I tried <code>ls -tr | head -n -5 | xargs rm</code> from the command line and it works successfully to delete older files if there are more than 5 in the directory.</p>
  
  <p>However, when I put it into my <code>for</code> loop, I get an error <code>rm: missing operand</code></p>
  
  <p>Here is the full script. I don't think I am using the <code>for</code> loop correctly in the script, but I'm really not sure how to use the commands <code>ls -tr | head -n -5 | xargs rm</code> in a loop that iterates over the files in the directory.</p>
  
  <pre><code>timestamp=$(date +"%m-%d-%Y")
  dest=${HOME}/mybackups
  src=${HOME}/safe
  fname='bu_'
  ffname=${HOME}/mybackups/${fname}${timestamp}.tar.gz
  
  # for loop for deletion of file
  for f in ${HOME}/mybackups/*
  do
    ls -tr | head -n -5 | xargs rm
  done
  
  if [ -e $ffname ];
    then
        echo "The backup for ${timestamp} has failed." | tee ${HOME}/mybackups/Error_${timestamp}
    else
        tar -vczf ${dest}/${fname}${timestamp}.tar.gz ${src}
  fi
  </code></pre>
  
  <p><strong>Edit: I took out the <code>for</code> loop, so it's now just:</strong></p>
  
  <pre><code>[...]
  ffname=${HOME}/mybackups/${fname}${timestamp}.tar.gz
  
  ls -tr | head -n -5 | xargs rm
  
  if [ -e $ffname ];
  [...]
  </code></pre>
  
  <p>The script WILL work if it is in the <code>mybackups</code> directory, however, I continue to get the same error if it is not in that directory.  The script gets the file names but tries to remove them from the current directory, I think...  I tried several modifications but nothing has worked so far.</p>