Overwriting file with sftp

I have a script, which runs through cronjob every night 9 PM. It is supposed to do following tasks --
1- Connect to ftp.testsite.com via user redtest
2- Fetch file red_bill.txt to my local server, where my script is residing.
3- Rename red_bill.txt to red_bill.V01.txt everyday on sftp server.
4- Make a copy of red_bill.txt on my local server
5- Send status mail to team.
Everything is ok, except 3. It seems, there is existing red_bill.V01.txt from previous night, so it is not able to overwrite that file. Can somebody help me with this script.

#!/bin/sh
HOST='ftp.testsite.com'
USER='redtest'
FILE='red_bill.txt'
cat > /tmp/script_file_$$ <<EOF
    get ${FILE}
    rename ${FILE} red_bill.V01.txt
    exit
EOF
 sftp -b /tmp/script_file_$$ $USER@$HOST
exit_status=$?
rm -f /tmp/script_file_$$
if [ $exit_status != 0 ];then
   echo "SFTP file transfer is failed for file $FILE" |mailx -s "FTP Redtest status"  xxxx@xxxx.com
else
echo "SFTP file transfer is successfull for file $FILE" |mailx -s "FTP Redtest status" xxxx@xxxx.com
cp $FILE $FILE.`date +%m%d%y`
fi

Why not delete the file and then rename it?

...
rm red_bill.V01.txt
rename ${FILE} red_bill.V01.txt
...

Where should I place these two lines ? Between get and exit as below ?

#!/bin/sh
HOST='ftp.testsite.com'
USER='redtest'
FILE='red_bill.txt'
cat > /tmp/script_file_$$ <<EOF
    get ${FILE}
    rm red_bill.V01.txt
    rename ${FILE} red_bill.V01.txt
    exit
EOF
 sftp -b /tmp/script_file_$$ $USER@$HOST
exit_status=$?
rm -f /tmp/script_file_$$
if [ $exit_status != 0 ];then
   echo "SFTP file transfer is failed for file $FILE" |mailx -s "FTP Redtest status"  xxxx@xxxx.com
else
echo "SFTP file transfer is successfull for file $FILE" |mailx -s "FTP Redtest status" xxxx@xxxx.com
cp $FILE $FILE.`date +%m%d%y`
fi

Thats right!

1 Like

Thanks