1

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"`

file=myfile

currdate=`date +%d`

currmon=`date +%m`

if [ -f $file ]

then

    echo "File exists."

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

    if [ $filedate -lt $currdate ]

    then

        echo "Old File"

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

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]
Aditya
  • 11
  • 3
  • 1
    Use YYYYMMDD format instead of DDMMYYYY – Barmar Aug 25 '16 at 19:52
  • 2
    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 http://unix.stackexchange.com/questions/134472/brackets-in-if-condition-why-am-i-getting-syntax-errors-without-whitespace – Gilles 'SO- stop being evil' 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

1 Answers1

1

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

linkname="abc.xyz"

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

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

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
Kusalananda
  • 333,661