We have a Unix job that runs for every hour in a day.

We want to update the script to create a new file everyday with same name (say abc.xyz), before creating it has to rename previous day's file with date time stamp (abc.xyz.12102014).

In 1st hour, if file is created, 2nd hour and so on, the same file (abc.xyz) has to be used.

On the next day (13102014), this file (abc.xyz) has to be renamed as abc.xyz.12102014 and new abc.xyz should be created, on 14102014 it has be renamed as abc.xyz.13102014.

I tried below, but got error at

if [ $filedate -lt $currdate ]

with 12 Command Not found, 12 is date from example above.

Please help me whats wrong in below script.

I am new to Unix hence used logic similar to what I use in C#.

Please tell me if there is any another way.

sdate=`date +%Y-%m-%d -d "yesterday"`


currdate=`date +%d`

currmon=`date +%m`

if [ -f $file ]


    echo "File exists."

    filedate=$(ls -l $file| awk '{ print $7}')

    if [ $filedate -lt $currdate ]


        echo "Old File"

        cp $file $file.$sdate
        rm $file
##something to do
##something to do

For dates at 30/31 of current month compared to 1st of next month, I can do the similar logic, but it again fails at

if [$filemonth -lt $currmonth]
  • Use YYYYMMDD format instead of DDMMYYYY – Barmar Aug 25 '16 at 19:52
  • 1
    That line cannot produce this error message. Post your actual, complete code (a shell script begins with a #! line) and the full error message. Add set -x as the second line of the script to get a trace of the commands it executes. Note that you need spaces inside the brackets, see unix.stackexchange.com/questions/134472/… – Gilles Aug 25 '16 at 22:44
  • Hello Gilles, Yes that line produced the error and I added spaces and it was fixed. To use DDMMYYYY is the requirement! I added a part of code, hence you are not able to see #! /bin/sh I will use the set -x and check it – Aditya Aug 26 '16 at 11:15

Instead of creating the file abc.xyz, create a symbolic link to the (real) file abc.xyz.YYYYMMDD:


today="$( date +"%Y%m%d" )"

if [[ ! -e "$filename" ]] || [[ ! -e "$linkname" ]]; then
    touch "$filename"
    ln -s -f "$filename" "$linkname"

This will create

lrwxr-xr-x  1 kk  kk  16 Feb  2 11:16 abc.xyz -> abc.xyz-20170202
-rw-r--r--  1 kk  kk   0 Feb  2 11:16 abc.xyz-20170202

and your program writing to abc.xyz will actually write to abc.xyz-20170202.

The next day when you run this, you'll get

lrwxr-xr-x  1 kk  kk  16 Feb  2 11:31 abc.xyz -> abc.xyz-20170203
-rw-r--r--  1 kk  kk   0 Feb  2 11:16 abc.xyz-20170202
-rw-r--r--  1 kk  kk   0 Feb  2 11:31 abc.xyz-20170203

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.