Using Trap in Unix Scripts - unix

I have written a script to transfer files from one server to another.
Firstly i am creating a tar of all the zipped files on one server and then i am transferring tar to another server.
Upon successful transfer i am doing Untar of files on both the sever.
I need to know one thing that how can i use Unix TRAP functionality in handling Restartability and Errors if anyhow tar file got corrupt of transfer got failed.
If any error exists i need to bring the execution back to its initial state.
Below mentioned is the small piece of code from my script
tar -cvf files_to_send.tar *.txt -C ${1}
RC=$?
if [ ${RC} -ne 0 ]; then
echo "Unable to Create Tar files of received files" >> ${LOG_FILE}
rm -f *_end >> ${LOG_FILE}
return 1
fi
cd ${1}
gzip files_to_send.tar
RC=$?
if [ ${RC} -ne 0 ]; then
echo "Unable to Create Zip of tar files" >> ${LOG_FILE}
echo "Deleting End Files" >> ${LOG_FILE}
rm -f *_end >> ${LOG_FILE}
echo "Deleting tar file" >> ${LOG_FILE}
rm -f ${1}/files_to_send.tar >> ${LOG_FILE}
return 1
fi
cd ${1}
chmod 775 files_to_send.tar.gz >> ${LOG_FILE}
RC=$?
if [ ${RC} -ne 0 ]; then
echo "Unable to change permissions of tar and end files" > ${LOG_FILE}
echo "Deleting End Files" >> ${LOG_FILE}
rm -f *_end >> ${LOG_FILE}
echo "Deleting Zipped tar file" >> ${LOG_FILE}
rm -f ${SOURCE_DIR}/files_to_send.tar.gz >> ${LOG_FILE}
return 1

You can do something like this :
trap 'do_something' ERR # start special error handling
tar ... # if the command fails, do_something will be executed
trap - ERR # stopping special error handling
do_something can be a function, a command or a script.
But you don't even need trap if you handle error cases properly. I wrote a version of your script with boolean logic, no need to store the return code in a variable, see :
if tar -cvf files_to_send.tar *.txt -C ${1}; then
echo "Unable to Create Tar files of received files" >> ${LOG_FILE}
rm -f *_end >> ${LOG_FILE}
return 1
fi
cd ${1}
if gzip files_to_send.tar; then
echo "Unable to Create Zip of tar files" >> ${LOG_FILE}
echo "Deleting End Files" >> ${LOG_FILE}
rm -f *_end >> ${LOG_FILE}
echo "Deleting tar file" >> ${LOG_FILE}
rm -f ${1}/files_to_send.tar >> ${LOG_FILE}
return 1
fi
cd ${1}
if chmod 775 files_to_send.tar.gz >> ${LOG_FILE}; then
echo "Unable to change permissions of tar and end files" > ${LOG_FILE}
echo "Deleting End Files" >> ${LOG_FILE}
rm -f *_end >> ${LOG_FILE}
echo "Deleting Zipped tar file" >> ${LOG_FILE}
rm -f ${SOURCE_DIR}/files_to_send.tar.gz >> ${LOG_FILE}
return 1
fi

Related

How to tell script to look only into a specific folder

I'm trying to make a recycle bin for UNIX, so I have two scripts. 1 to delete the file and move it to the bin, the other script to restore the file back to its original location.
my restore script only works if the person gives the path to the deleted file.
ex: sh restore ~/trashbin/filename
How do I hardcode into my script so that I don't need to give the path to the deleted file it should already know to look in the trashbin for the file. My restore script works only when someone calls in the path to the file.
#!/bin/bash
rlink=$(readlink -e "$1")
rname=$(basename "$rlink")
function restoreFile() {
rlink=$(readlink -e "$1")
rname=$(basename "$rlink")
rorgpath=$(grep "$rname" ~/.restore.info | cut -d":" -f2)
rdirect=$(dirname "$rorgpath")
#echo $orgpath
if [ ! -d "$rdirect" ]
then
mkdir -p $rdirect
#echo $var
mv $rlink $rorgpath
else
mv $rlink $rorgpath
fi
}
if [ -z "$1" ]
then
echo "Error no filename provided."
exit 1
elif [ ! -f "$1" ]
then
echo "Error file does not exist."
exit 1
elif [ -f "$rorgpath" ]
then
echo "File already exists in original path."
read -p "Would you like to overwrite it? (y/n)" ovr
if [[ $ovr = y || $ovr = Y || $ovr = yes ]]
then
echo "Restoring File and overwriting."
restoreFile $1
grep -v "$rname" ~/.restore.info > ~/.restorebackup.info
mv ~/.restorebackup.info ~/.restore.info
fi
else
echo "Restoring file into original path."
restoreFile $1
grep -v "$rname" ~/.restore.info > ~/.restorebackup.info
mv ~/.restorebackup.info ~/.restore.info
fi
When you "remove" the file from the file-system to your trash-bin, move it so that its path is remembered. Example: removing file /home/user/file.txt should mean moving this file to ~/.trash/home/user/file.txt. That way, you'll be able to restore files to the original location, and you'll have auto-complete work, since you can do: sh restore ~/.trash/<TAB><TAB>

Creating a .sh file through Batch script and executing .sh file through batch

Below is the part of a batch script that i have created:
{
REM ********* CONN SCRIPT CREATION ***************
echo #!/bin/sh >%conn_script%
echo >>%conn_script%
echo if [ %today% -eq 23 ] >>%conn_script%
echo then >>%conn_script%
echo **find . -maxdepth 0 -type f -mtime +0 -exec rm -rf {} \;>>%conn_script%
echo else >>%conn_script%**
echo echo Files are not from previous month >>%conn_script%
echo fi >>%conn_script%
type %conn_script%
::echo bye >>%conn_script%
echo The sftp_script is:
echo "command: call %executor%\RUN\plink -ssh %host% -batch -l %user% -pw ********** -m %conn_script%"
call %executor%\RUN\plink -ssh %host% -batch -l %user% -pw %password% -m %conn_script% >%logfile%
}
I have created a batch script that is creating a .sh file. That sh file is deleting files from a unix server. When batch script is executing sh file it is getting error "find: bad option -maxdepth
find: [-H | -L] path-list predicate-list" from the code which is in BOLD format.
Even i also want to append the log of deleted files in a .txt file which is in my local machine.
I have tried a lot but not able to append the log in .txt file.
Please provide yours valuable feedback for this issue.
Thanks
Have you tried /usr/xpg4/bin/find (Available in Solaris).
/usr/xpg4/bin/find . -maxdepth 0 -type f -mtime +0 | xargs rm -f

Unix Loop if Condition and exit comand

I am facing an issue, I have to delete files from some folders given in Path.lst,
The entire script is working fine but when some wrong path is given in Path.lst the script does exits out of the loop and perform no operation on the next paths.
But the last line
echo -e "\n ENDING SCRIPT SUCCESSFULLY ON `date` " >> $LOG_FILE
gets executed because exit 1 is not working in this part
if [ ! -d $path ]
then
echo -e "\nERROR :$path IS INVALID." >> $LOG_FILE
echo -e "\nENDING SCRIPT WITH ERRORS ON `date`" >> $LOG_FILE
exit 1
---------------------------------------------------------------------------------------
THE SCRIPT IS LIKE :
echo -e "\nSTARTING SCRIPT ON `date`">> $LOG_FILE
if [ $1 -gt 0 ]
then
DAYS_BFOR="$1"
else
echo -e "\nERROR :Please pass a single positive integer to the script" >>$LOG_FILE
echo -e "\nENDING SCRIPT WITH ERRORS ON `date` " >> $LOG_FILE
exit
fi
cat Path.lis | sed 's|^PATH[0-9]*=||g' | while read path
do
if [ ! -d $path ]
then
echo -e "\nERROR :$path IS INVALID." >> $LOG_FILE
echo -e "\n ENDING SCRIPT WITH ERRORS ON `date` " >> $LOG_FILE
exit 1
else
echo -e "\nFILES DELETED FROM THE "$path" DIRECTORY --" >> $LOG_FILE
find $path -type f -mtime +$DAYS_BFOR -printf "%TY-%Tm-%Td %kKB %p\n" | column -t | sed "s|"$path"||g" >> $LOG_FILE 2>&1
file_count=`find $path -type f -mtime +$DAYS_BFOR | wc -l`
if [ $file_count -ge 1 ]
then
find $path -type f -mtime +$DAYS_BFOR | xargs rm 2>>$LOG_FILE 2>&1
fi
fi
done
echo Exit Status : $?
echo -e "\n ENDING SCRIPT SUCCESSFULLY ON `date`" >> $LOG_FILE
Please help and explain the reason as well.
If you only want the "ENDING SCRIPT SUCCESSFULLY" message to appear if files were successfully deleted, not if an invalid path was given you could just move the last two echo lines up to the end of the else statement like this:
else
echo -e "\nFILES DELETED FROM THE "$path" DIRECTORY --" >> $LOG_FILE
find $path -type f -mtime +$DAYS_BFOR -printf "%TY-%Tm-%Td %kKB %p\n" | column -t | sed "s|"$path"||g" >> $LOG_FILE 2>&1
file_count=`find $path -type f -mtime +$DAYS_BFOR | wc -l`
if [ $file_count -ge 1 ]
then
find $path -type f -mtime +$DAYS_BFOR | xargs rm 2>>$LOG_FILE 2>&1
fi
echo Exit Status : $?
echo -e "\n--------------------------- ENDING SCRIPT SUCCESSFULLY ON `date` ----------------------------------" >> $LOG_FILE
fi
done
If you want to just skip to the next item in the Path.lis file then just remove the exit statement from the first loop. That way it will continue to execute the script until all the lines in the file have been read, and just show an error if the current file is not a valid path.

UNIX - Moving a deleted file back to it's original directory

All I want to do is move a file from my created recycle bin to it's own original path.
My code is as follows:
#!/bin/bash
restore ()
{
base=`basename $restore_file | cut -d"_" -f1`
echo "Your file $base has been restored"
mv deleted/$restore_file /$HOME/$base
}
restore_file=$1
if [ $# -eq 0 ]
then
echo "You have not entered a file"
elif [ -e deleted/$restore_file ]
then
restore
grep -v $(basename $restore_file) $HOME/.restore.info >> $HOME/.restore.inf o.tmp
cp $HOME/.restore.info.tmp $HOME/.restore.info
rm $HOME/.restore.info.tmp
else
echo "Your file "$restore_file" does not exist"
fi
I'm sure the error is in on line 7, just not sure how to rewrite. Any ideas?
Do you need to put a full path in before deleted?
You don't need the slash before $HOME, but that shouldn't be a problem.

unix shell script creating backup.sh

How to write a shell script named "backup.sh" which accepts one parameter, which would be a filename/directory.
Create a backup copy of that with the .bak appended to its name.Show message on success.
If the file/directory does not exist, show a proper message.
i did up to this point.please help me to figure this out
#!/bin/sh
#create_backup.sh
And add a .bak
bak="${backup.sh}.bak"
if [ "$#" -eq 0 ]
then
exit 1;
echo "File Succesfully backuped"
fi
cp ${1} "${1}.back"
echo "File is not found "
exit 0
#!/bin/bash -e
directory=$1
cp -r $directory $directory.bak
echo "Success"
obvious caveats with pathing/error codes/etc

Resources