Trap explanation?

 
Thread Tools Search this Thread
Top Forums UNIX for Beginners Questions & Answers Trap explanation?
# 1  
Old 10-03-2017
Trap explanation?

Hi Folks -

Could someone help me understand something about my trap statement? I've been using the following trap statement for a while now and its works perfectly. The first part of the shell scripts look like such:

Code:
source "/home/EPMTrain1/Hyperion_Batch/Scripts/Batch/_env.sh"

#::-- Set Log & Error subdirectories pertaining to the specific process --::#
_PLOGPATH=Auto_Train_Logs/
_PERRORPATH=Auto_Train_Errors/

#::-- Establish STDOUT and STDERROR repositories --::
_INTRAPATH=${_LOGPATH}${_PLOGPATH}${_YEAR}_${_MONTH}${_DAY}
_ERRORINTRAPATH=${_ERRORPATH}${_PERRORPATH}${_YEAR}_${_MONTH}${_DAY}
    
mkdir -p "${_INTRAPATH}"
mkdir -p "${_ERRORINTRAPATH}"

#::-- Prepare File Name Format --::#
#::   _SN          = Script Name with extension
#::   ${_SN%%.sh*} = Script name without extension
#::   _FN          = File Name

_SN=${0##*/}
_FN=${_DATESTAMP}_${_TIME}_${_SN%%.sh*}

#::-- Establish STDOUT and STDERROR files --::#
_LOGFILE=${_INTRAPATH}/${_FN}.log
_ERRORFILE=${_ERRORINTRAPATH}/${_FN}.err
_MAXLLOGFILE=${_INTRAPATH}/${_FN}_MAXL.log

#::-- Direct STDOUT and STDERROR to repositories --::# 
exec 2>"${_ERRORFILE}" > "${_LOGFILE}"

#::-- If empty, delete YYYY_MMDD error file subdirectory --::
trap "[ -s ${_ERRORFILE} ] || rm -f ${_ERRORFILE} && rmdir ${_ERRORINTRAPATH}" EXIT

My question is, in the trap argument, if ${_ERRORFILE} doesn't exist, it will proceed to the next command in the argument. but if it doesn't exist, why would I need to "remove it" again? Obviously it will always result in a "0" of that command since I"m forcing it (and thus, will proceed due to &&) but I'm just curious.

Perhaps someone can explain it so it makes more sense to me? Thanks!

Last edited by rbatte1; 10-03-2017 at 09:34 AM..
# 2  
Old 10-03-2017
Hi,

test -s checks if the file exists and its size is greater than zero.
So if the file exists but is empty it will be removed.
# 3  
Old 10-03-2017
But if the file doesn't exist, that condition fails then thus, will execute the command on the right side of the ||. Therefore, why is a rm -f necessary here?

---------- Post updated at 07:58 AM ---------- Previous update was at 07:52 AM ----------

Perhaps in case the file is empty? Ah i see.
# 4  
Old 10-03-2017
Of course, this only runs at the end of the script (i.e. the EXIT point of the shell)

Is there anything else in the script or is this the last operation? If it is, then I would get rid of the trap altogether or put it up at the top so it cleans up if your script aborts somewhere.



Robin
# 5  
Old 10-03-2017
Hi Robin -

Thanks for the note! I'm sorry I wasn't clear - this is at the top of my script. My former code snippet was just a portion.

Here is my full script:

Code:
#!/bin/bash
#::--:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::#
#::-- Script Name: EPMTrain1.sh                                               --::#
#::                                                                           --::#
#::-- Description: Allows functionality to Login to Essbase                   --::#
#::                                                                              --::#
#::                                                                              --::#
#::                                                                              --::#
#::--  Calls:      _env.sh                                                    --::#
#::--  Called By:  N/A                                                        --::#
#::                                                                              --::#
#::-- Parameters:  Not Applicable                                               --::#
#::                                                                              --::#
#::-- Author:      Name                                                     --::#
#::-- Date:                                                                       --::#
#::                                                                              --::#
#::--:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::#

source "/home/EPMTrain1/Hyperion_Batch/Scripts/Batch/_env.sh"

#::-- Set Log & Error subdirectories pertaining to the specific process --::#
_PLOGPATH=Auto_Train_Logs/
_PERRORPATH=Auto_Train_Errors/

#::-- Establish STDOUT and STDERROR repositories --::
_INTRAPATH=${_LOGPATH}${_PLOGPATH}${_YEAR}_${_MONTH}${_DAY}
_ERRORINTRAPATH=${_ERRORPATH}${_PERRORPATH}${_YEAR}_${_MONTH}${_DAY}
    
mkdir -p "${_INTRAPATH}"
mkdir -p "${_ERRORINTRAPATH}"

#::-- Prepare File Name Format --::#
#::   _SN          = Script Name with extension
#::   ${_SN%%.sh*} = Script name without extension
#::   _FN          = File Name

_SN=${0##*/}
_FN=${_DATESTAMP}_${_TIME}_${_SN%%.sh*}

#::-- Establish STDOUT and STDERROR files --::#
_LOGFILE=${_INTRAPATH}/${_FN}.log
_ERRORFILE=${_ERRORINTRAPATH}/${_FN}.err
_MAXLLOGFILE=${_INTRAPATH}/${_FN}_MAXL.log

#::-- Direct STDOUT and STDERROR to repositories --::# 
exec 2>"${_ERRORFILE}" > "${_LOGFILE}"

#::-- If empty, delete YYYY_MMDD error file subdirectory --::
trap "[ -s ${_ERRORFILE} ] || rm -f ${_ERRORFILE} && rmdir ${_ERRORINTRAPATH}" EXIT

#::-- Begin Script Processing --::#
echo ---------------------------------------------
echo "${_SN} beginning at ${_TIME}"                           
echo ---------------------------------------------
echo ---------------------------------------------                                                                                            
echo "Check for flag file"                                         
echo ---------------------------------------------

_FLAGFILE=${_FLAGFILEPATH}EPMTrain1.txt

if [ -e "${_FLAGFILE}" ]
then
    echo
    echo "Flag file detected"
    echo "Unable to proceed - exiting shell session"
    echo
    sleep 10
    exit 0
else
    echo
    echo "Flag file not detected - now establishing flag file"
    echo "Proceeding with script execution"
    echo
    echo "FlagFile">>"${_FLAGFILE}"
fi

echo ---------------------------------------------------------                                                                                                
echo "Login to ${_ESSB_SRVR}"                                         
echo ---------------------------------------------------------

. "${_STARTMAXLPATH}startMaxl.sh" "${_MAXLSCRIPTPATH}AC.mxl" ${_ESSB_USER} ${_ESSB_PSWD} ${_ESSB_SRVR} ${_MAXLLOGFILE}
_RVAL=$?

if [ $_RVAL -eq 0 ]
then
  echo ---------------------------------------------------------
  echo "Login to ${_ESSB_SRVR} : Successful"                           
  echo ---------------------------------------------------------
  
else
  echo ---------------------------------------------------------
  echo "Login to ${_ESSB_SRVR} : Unsuccessful"                      
  echo ---------------------------------------------------------
  exit 1
  fi

echo ---------------------------------------------------------                                                                                                
echo "Delete flag file"                                         
echo ---------------------------------------------------------
echo

rm -f "${_FLAGFILE}" && echo "Flag file deleted" || echo "Flag file did not exist"

echo
echo ---------------------------------------------------------                                                                                                
echo "${_SN} - Completed Successfully"
echo
echo "Normal Exit"                                        
echo ---------------------------------------------------------
exit 0

# 6  
Old 10-03-2017
That looks almost char-for-char identical to code I wrote a few months ago. It began when simplifying their code with this:

Code:
exec 2>"${_ERRORFILE}" > "${_LOGFILE}"

They were thrilled they didn't have to do echo ... >> logfile and command 2>>errorlogfile every single time, but they didn't like that _LOGFILE was always created even when no errors occurred. So I added the trap to clean up the log file at exit unless it had greater-than-zero size.
# 7  
Old 10-03-2017
Corona -

Yes that was me Smilie It's been working fantastically!!!!

I was just having trouble understanding it for some reason, that's all.

Thank you!
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Need explanation

Hi, I need more explination on it, how it works abcd="$(echo "$abcd" | sed 's/ //g')" >> ${LOGFILE} 2>&1 can any one suggest me on this? Rgds, LKR (1 Reply)
Discussion started by: lakshmanraok
1 Replies

2. Homework & Coursework Questions

VM trap may work differently than a pure install trap.

Use and complete the template provided. The entire template must be completed. If you don't, your post may be deleted! 1. The problem statement, all variables and given/known data: That is the last reply I received from my instructor, and I'm looking for some alternatives. When using... (2 Replies)
Discussion started by: newuser45
2 Replies

3. UNIX for Dummies Questions & Answers

In need of explanation

Its great someone provided this script that strips out a filename and extension but can someone explain how each line works? file1='Jane Mid Doe.txt' newfile='Jane.txt' 1) ext=${file1##*.} 2) filename=${file%%.???} 3) set -- $filename 4) newfile="1.$extension" (1 Reply)
Discussion started by: Lillyt
1 Replies

4. Shell Programming and Scripting

Cntl+z Trap is not detecting ??? Help required to add a trap detection ???

Hi folks, I have tried to add some trap detection in the below script....this script is used to monitor database activities...in a rather awkward way :rolleyes:.... The idea behind adding trap is that....this script creates lots of temporary files in the running folder to store the count... (1 Reply)
Discussion started by: frozensmilz
1 Replies

5. Shell Programming and Scripting

How to trap

I have a script #!/bin/ksh trap cleanup 20 cleanup() { cat $t.log echo Caught exit 1 } if ;then echo Found >>t.log exit 20 else echo Not found >>t.log exit 20 fi (5 Replies)
Discussion started by: thana
5 Replies

6. UNIX and Linux Applications

need explanation

Hi am having a c pgm. It has the include files (unistd.h,sys/types.h,win.h,scr.h,curses.h,stdarg.h and color.h). I don't know the purpose of these include files. will u plz explain me. (1 Reply)
Discussion started by: Mari.kb
1 Replies

7. UNIX for Advanced & Expert Users

Need help with trap

Hi Our problem is knowing: What is the "best" way of simulating a TRAP for ERR within a function, since we know this will not work directly with ksh93 and aix5. How can we save the error encountered in the function and then deal with it in the calling script? Thanks! (3 Replies)
Discussion started by: theteeth07
3 Replies

8. Shell Programming and Scripting

tr explanation please

how does below tr command replace nonletters with newlines? I think I understand tr -cs '\n' part.. but what is A-Za-z\' <--- what is this?? tr -cs A-Za-z\' '\n' | -c --complement -s, --squeeze-repeats replace each input sequence of a repeated character that is... (1 Reply)
Discussion started by: convenientstore
1 Replies

9. Shell Programming and Scripting

tr explanation please

how does below tr command replace nonletters with newlines? I think I understand tr -cs '\n' part.. but what is A-Za-z\' <--- what is this?? tr -cs A-Za-z\' '\n' | -c --complement -s, --squeeze-repeats replace each input sequence of a repeated character that is... (0 Replies)
Discussion started by: convenientstore
0 Replies

10. Shell Programming and Scripting

Building a better mouse trap, or How many lines of code does it take to trap a mouse?

Hello all, I'm hoping to get a little insight from some of the wily veterans amongst you. I've written a script to check for new outgoing files to our vendors located on our ssl server. It seems to be working ok, but the final question here, will be one of logic, and/or a better way to... (4 Replies)
Discussion started by: mph
4 Replies
Login or Register to Ask a Question