Script to move file on a daily basis

Hi!

Please I need help on the a script that would pick one file in a directory, change its name, them change its permissions, them move to a different directory, but has to be done on a daily basis, and the file that is being moved to its final destination has to have the following format:

xxxx_yyyy20140424.csv

, this is for today, and tomorrow must be

xxxx_yyyy20140425.csv

.

What I have wrote so far was:

#!/usr/bin/ksh
echo
#change permissions of a file
/usr/bin/chmod 777 /directory/subdirectory/File.csv
echo
#change file name
/usr/bin/mv File.csv xxxx_yyyy

I am stuck in that last line of the script.

cd org_dir
_Y='%Y'
_y='%Y'
_m='%m'
_d='%d'
TIMESTAMP=`date "+$_Y$_m$_d"`
chmod 777 file.csv
mv file.csv /dest_dir/xxxx_$TIMESTAMP.csv 

---------- Post updated at 04:15 AM ---------- Previous update was at 04:09 AM ----------

Additionaly you can use cronjob to call the script daily

1 Like

How do I add a funtionality to warn me when a file was not moved to its destination directory, or if the script has failed.

Add this at the end of the code

if [ -f ../dest_dir/xxxx_$TIMESTAMP.csv ]; then
echo "Moved"
else
echo "Not Moved"
fi
 
if [ $? -ne 0 ] # exit status is not 0
then
  echo "Error while transfering file at $(date)"
  exit $?
fi

If any command fails control will come in this if block

---------- Post updated at 09:58 AM ---------- Previous update was at 09:50 AM ----------

Updated Code

cd newfolder
_Y='%Y'
_y='%Y'
_m='%m'
_d='%d'
TIMESTAMP=`date "+$_Y$_m$_d"`
chmod 777 file.csv
mv file.csv ../dest_dir/xxxx_$TIMESTAMP.csv
if [ -f ../dest_dir/xxxx_$TIMESTAMP.csv ]; then
echo "Moved"
else
echo "Not Moved"
fi
 
if [ $? -ne 0 ] # exit status is not 0
then
  echo "Error while transfering file at $(date)"
  exit $?
fi

I have put the script on a crontab, so that can be run 1AM, everyday, so I beleive the error message must come in an email format

No it will not. how it will automaticaly come in email format.
you have to write

if [ $? -ne 0 ] # exit status is not 0
then
  echo "Error while transfering file at $(date)"
  echo "Error Occured" | mailx -s "Error" abc@xyz.com
  exit $?
fi
1 Like

will that piece of code come in the second check

if

or first?

Or put in first check

if [ -f ../dest_dir/xxxx_$TIMESTAMP.csv ]; then
echo "Moved"
echo "Success:File Moved" | mailx -s "Success" abc@xyz.com
else
echo "Not Moved"
echo "Error Occured:File not moved" | mailx -s "Error" abc@xyz.com

fi

1 Like