title: Rollover shell script
body: <p>Assuming a shell script(commands.sh) with few commands.</p>
  
  <p>I need to write a script which sends the output of commands executed by commands.sh to a file f1.csv
  if file size exceeds 1MB then the output flowing should go to  file f2.csv
  if the file size exceeds 1 mb again here,the output flowing should go to file f3.csv
  if f3.csv exceeds the size 1mb,then the older f1 should be deleted and again new file f1 should be created,
  output flowing should be to written to f1. This process should go on .</p>
  
  <p>I can write the crontab file, just the shell script is a bit tricky</p>
  
  <p>I have been experimenting:</p>
  
  <pre><code>#!/usr/bin/env bash
  
  PREFIX="f"
  # Maximum size after which you want a new file in bytes
  MAX_SIZE=1048576
  LAST_FILE=`ls "$prefix"*.csv | tail -1`
  # Check if file exists and if it does not, create it.
  if [[ -z "$LAST_FILE" ]]
    then
    LAST_FILE=$PREFIX"1.csv"
    touch $LAST_FILE
  fi
  LAST_FILE_NO=`echo $LAST_FILE | sed s/$PREFIX/''/ | sed s/.csv/''/`
  LAST_FILE_SIZE=`stat -c %s $LAST_FILE`
  
  
  if [ `stat -c %s $LAST_FILE` -lt 200 ]
    then
       `/bin/sh ./sam.sh &gt;&gt; $LAST_FILE`
    else
      UPCOMING_FILE_NO=$((LAST_FILE_NO+1))
      `/bin/sh ./sam.sh &gt;&gt; $PREFIX$UPCOMING_FILE_NO.csv`
  fi
  </code></pre>
  
  <p>help is appreciated guys.</p>
  
  <p>EDIT: Have got the secondary shell script to work too...
  Now if anyone could help me with resetting after 3 files are done and starting from f1. </p>
  
  <p>thanks</p>