Unix Loop if Condition and exit comand - unix

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.

Related

SED command use for writing back to the same file

I have the below code which adds Logger.info line after every function definition which I need to run on a python script which is the requirement.
The only question is this has to be written back to the same file so the new file has all these looger.info statements below each function definition.
e.g. the file abc.py has currently below code :
def run_func(sql_query):
return run_func(sql_query)
and the code below should create the same abc.py file but with all the logger.info added to this new file
def run_func(sql_query):
LOGGER.info (''MIPY_INVOKING run_func function for abc file in directory'
return run_func(sql_query)
I am not able to write the sed in this file to the new file (with same file name) so that the original file gets replaced by same file name and so that I have all the logger.info statements in there.
for i in $(find * -name '*.py');
do echo "#############################################" | tee -a auto_logger.log
echo "File Name : $i" | tee -a auto_logger.log
echo "Listing the python files in the current script $i" | tee -a auto_logger.log
for j in $(grep "def " $i | awk '{print $2}' | awk -F"(" '{print $1}');
do
echo "Function name : $j" | tee -a auto_logger.log
echo "Writing the INVOKING statements for $j function definition" | tee -a auto_logger.log
grep "def " $i |sed '/):/w a LOGGER.info (''INVOKING1 '"$j"' function for '"$i"' file in sam_utilities'')'
if [ $? -ne 0 ] ; then
echo " Auto Logger for $i filename - Not Executed Successfully" | tee -a auto_logger.log
else
echo "Auto Logger for $i filename - Executed Successfully" | tee -a auto_logger.log
fi
done
done

recovering deleted script running in background

I have script which is running in bg(nohup) but it was accidently deleted,but that is continue running now I need to edit the code which is already deleted.
How can I now get that code.I assume somewhere it should be as it is running.
Try this :
#!/bin/bash
if [[ ! $1 || $1 == -h || $1 == --help ]]; then
echo -e "Usage:\n\n\t$0 '[path/]<file name>'"
exit 1
fi
files=(
$(file 2>/dev/null /proc/*/fd/* |
grep "(deleted)'$" |
sed -r 's#(:.*broken\s+symbolic\s+link\s+to\s+.|\(deleted\).$)# #g' |
grep "$1" |
cut -d' ' -f1
)
)
if [[ ${files[#]} ]]; then
for f in ${files[#]}; do
echo "fd $f match... Try to copy this fd to another place quickly!"
done
else
echo >&2 "No matching fd found..."
exit 2
fi
Not tested on non GNU-Linux

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

Using Trap in Unix Scripts

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

Remove duplicate jars in a directory

I have a script to remove lower version jars files in a directory.
#!/bin/bash
#Script to remove lower version jar files.
for PREFIX in `ls *.jar|sed 's/-[0-9\.\0-9\.a-zA-Z]*\.jar//g'|uniq -d`; do
for FILE in `ls -r ${PREFIX}*|sed '1d'`; do
echo " $FILE"
rm $FILE
done
done
It has a bug.
I have below list of Duplicate jar files in a directory.
xyz-1.1.jar
xyz-1.1.1.jar
abc-1.6.jar
abc-1.3.jar
abc-xyz-pqr-1.9.6.jar
abc-xyz-pqr-1.9.2.jar
xyz-tom.jar
xyz-tom-20120423.jar
xyz-tom-20120410.jar
abc-toolkit-1.6-runtime-5.2.0.jar
abc-toolkit-1.6-runtime-5.0.0.jar
The bug is with xyz pattern jar files.
BUG:
Script is removing xyz-1.1.1.jar file instead of xyz-1.1.jar
Script is removing xyz-tom-20120423.jar and xyz-tom-20120410.jar files.
#!/bin/bash
if [ $# == 0 ]; then
dir='.'
elif [ $# == 1 ]; then
dir=$1
else
echo "Usage: $0 [dir]";
exit 1;
fi
for lib in `find $dir -name '*.jar'`; do
for class in `unzip -l $lib | egrep -o '[^ ]*.class$'`; do
class=`echo $class | sed s/\\\\.class// | sed s/[-.\\/$]/_/g`
existing=$( eval "echo \$CLS_${class}" )
if [ -n "$existing" ]; then echo "$lib $existing"; fi
eval CLS_${class}="\"${lib} ${existing}\""
done
done | sort | uniq -c | sort -nr
I find this code here

Resources