# # ============================================================================= # Syntax Usage examples for some of the functions in scriptt.sh # ============================================================================= # # Note: you can delete the function "SyntaxHelp" in your script if applicable # # ----------------------------------------------------------------------------- # General hints # Use scriptt.sh -H 2>./scriptt.doc to create the documentation for scriptt.sh including the infos for all public variables and functions that can be used. Use the function "YourRoutine" as template for new functions. Use the function "USER_SIGNAL_HANDLER" as template for new signal handler. Use the format function [function_name] { ... } to define new functions to be compatible with ksh88 and ksh93. Be aware that the return code for a function is an integer value between 0 and 255 Define all local variables in functions using typeset [varname][=value] Do NOT define new variables beginning with two underscore "__"! To source in another script you should only use the function includeScript instead of ". " # ----------------------------------------------------------------------------- # sample code for using the house keeping routines # # create a temporary mount point or directory mkdir "${TMPDIR}" && __LIST_OF_TMP_DIRS="${__LIST_OF_TMP_DIRS} ${TMPDIR}" || LogError "Error creating the directory \"${TMPDIR}\" " # create a temporary file touch "${TMPFILE}" && __LIST_OF_TMP_FILES="${__LIST_OF_TMP_FILES} ${TMPFILE}" || LogError "Error creating the file \"${TMPFILE}\" " # add a function to the house keeping (to be executed before files, directories, and mounts are removed) # Use "function_name:parameter1[[...]:parameter#] to add parameter for a function # blanks or tabs in the parameter are NOT allowed __EXITROUTINES="${__EXITROUTINES} [your_function]" # or (to be executed after files, directories, and mounts are removed) # Use "function_name:parameter1[[...]:parameter#] to add parameter for a function # blanks or tabs in the parameter are NOT allowed __FINISHROUTINES="${__FINISHROUTINES} [your_function]" # ----------------------------------------------------------------------------- # To log a message you may use one of the functions # # LogMsg, LogInfo, LogWarning, LogError, LogOnly, LogIfNotVerbose # # To log a message without timestamp use LogMsg "-" "[your message]" # To Log a message in verbose mode (parameter -v) use LogInfo "[your message]" # or LogInfo 0 "[your message]" # To log a message only in a more verbose mode (parameters -v -v) use LogInfo 1 "[your message]" # To log a message only in a more verbose mode (parameters -v -v -v) use LogInfo 2 "[your message]" # To Print only a dot (or any other character) without a line feed use PrintDotToSTDOUT # To add a timestamp to all messages from a binary or script you can use PrintWithTimestamp vmstat 1 5 # use StartStop_LogAll_to_logfile to log STDERR and STDOUT of all running programs to a logfile # start logging StartStop_LogAll_to_logfile start "/var/tmp/newlogfile" # this messages is only written to the logfile echo "### Logging started" # write a message to STDOUT echo "This message goes to STDOUT and not in the log file " >&3 # do whatever is necessary ... (all output of the commands is only written to the logfile) ls ls /dfafdsa uname -a # exeucte a command with "normal" STDOUT and STDERR ls /dasff 2>&4 1>&3 # write a message to STDERR echo "This message goes to STDERR and not in the log file " >&4 # this messages is only written to the logfile echo "### Logging will be stopped now" # stop logging StartStop_LogAll_to_logfile stop echo "Logging disabled again." # To get some input from the user the function AskUser might be used AskUser "Start (y/N)?" if [ $? -eq ${__TRUE} ] ; then echo "User response was yes" else echo "User response was not yes" fi # or AskUser "Your input please:" echo "User response is \"${USER_INPUT}\" " # AskUser supports an internal debug shell; to start the debug shell enter "shell", e.g. # [01.11.2014 14:01:05] Using the log file "/var/tmp/scriptt.log" Start (y/N)? shell ------------------------------------------------------------------------------- scriptt.sh - debug shell - enter a command to execute ("exit" to leave the shell) >> # The debug shell can be used to view or change global variables in your script. # use # executeCommandAndLog # to execute other scripts and binaries. This function logs STDOUT and STDERR # to the logfile. The return code is the returncode of the executed script/binary # (use executeCommandAndLogSTDERR to only log STDERR) executeCommandAndLog "ls ${__SCRIPTNAME}" LogMsg "The returncode is $?" executeCommandAndLog "ls \dasfdsaf" LogMsg "The returncode is $?" # To work with dynamically defined functions the template implements the functions: # IsFunctionDefined # and # executeFunctionIfDefined # e.g. IsFunctionDefined SyntaxHelp if [ $? -eq ${__TRUE} ] ; then SyntaxHelp die 0 else die 232 "Function SyntaxHelp NOT defined." fi # to work with userid and groups you can use the functions # UserIs, GetCurrentUID, GetUserName, and GetUID # to work with dates the template contains the functions # GetOtherDate, ConvertDateToEpoc, GetTimeStamp, GetSeconds, GetMinutes, and ConvertMinutesToHours # Use push and pop to temporary save the contents of a variable: # (push and pop use a LIFO stack structure; there is only one global stack # with up to 255 elements) # VAR1=var1 VAR2=var2 VAR3=var3 echo "Variable VAR1 is \"${VAR1}\", VAR2 is \"${VAR2}\", and VAR3 is \"${VAR3}\" " # save the contents of the variables VAR1 and VAR2 push "${VAR1}" "${VAR2}" # save the contents of the variable VAR3 and then set VAR3 to 99 push_and_set VAR3 99 # now you can work with the variables VAR1, VAR2, and VAR3 # ... VAR2=88 VAR1=100 echo "Variable VAR1 is \"${VAR1}\", VAR2 is \"${VAR2}\", and VAR3 is \"${VAR3}\" " # restore the contents of the variables VAR1, VAR2, and VAR3: pop VAR3 VAR2 VAR1 echo "Variable VAR1 is \"${VAR1}\", VAR2 is \"${VAR2}\", and VAR3 is \"${VAR3}\" " # use CheckInputDevice to check if the script is running in a terminal session # or for example as cron job # CheckInputDevice if [ $? -eq ${__TRUE} ] ; then echo "Standard input is a terminal" else echo "Standard input is NOT a terminal" fi # Use the string manipulation functions # substr, replacestr, pos, lastpos, toUppercase, and toLowercase # to work with strings, e.g.: # function replacestr # STR="1234567890" SUBSTR="456" replacestr $STR $SUBSTR "Arno Teunisse" TT [ $? == 0 ] && echo $TT # should show in $TT : "123Arno Teunisse7890" # function pos # STR="Arno Teunisse" SUBSTR="o" pos $SUBSTR $STR [ $? -gt 0 ] && echo $? # Most of the string functions support an optional parameter for the result string, # so you can use substr for example either this way # variable=$( substr sourceStr pos length ) # or this way # substr sourceStr pos length resultVariable # e.g. RESULTVAR="" SOURCESTRING=12345abcdefg" POS=6 LENGTH=3 substr "${SOURCESTRING}" ${POS} ${LENGTH} "RESULTVAR" echo "RESULTVAR is now \"${RESULTVAR}\" " # is the same as RESULTVAR="$( substr "${SOURCESTRING}" ${POS} ${LENGTH} )" echo "RESULTVAR is now \"${RESULTVAR}\" " # use the convert routines # ConvertToOctal, ConvertoBinary, and ConvertToHex # to convert a value into octal, binary, or hexadecimal format DECIMAL_VALUE=23 LogMsg "${DECIMAL_VALUE} in Octal is $( ConvertToOctal ${DECIMAL_VALUE} )" LogMsg "${DECIMAL_VALUE} in Binary is $( ConvertToBinary ${DECIMAL_VALUE} )" LogMsg "${DECIMAL_VALUE} in Hexadecimal is $( ConvertToHex ${DECIMAL_VALUE} )" # ----------------------------------------------------------------------------- # and last some sample code snippets for ksh88 ... # # count words in a string # # this code returns 5 noOfWords=$( set -- This is a Test String ; echo $# ) # this code returns 1 noOfWords=$( set -- "This is a Test String" ; echo $# ) # get the current date & time # source: http://cfajohnson.com/shell/tuesday-tips/#tt-2004-07-06 # eval "$( date "+DATE=%Y-%m-%d YEAR=%Y MONTH=%m DAY=%d TIME=%H:%M:%S HOUR=%H MINUTE=%M SECOND=%S datestamp=%Y-%m-%d_%H.%M.%S DayOfWeek=%a MonthAbbrev=%b")" # replace a character with another character with ksh internals # -> replace ":" with "#" in the PATH variable # NEW_STRING=$( IFS=: ; printf "%s#" $PATH ) # read the 1st line of a file # IFS="$( printf "\n" ; )" read LINE1 replace ":" with "#" in the PATH variable # NEW_STRING="${PATH//:/#}" # sample for loop over 1 to 10 # for i in {1..10} ; do echo $i done # builtin time formatting in printf in ksh93: # see http://blog.fpmurphy.com/2008/10/ksh93-date-manipulation.html: # The ksh93 builtin printf (not printf(1)) includes a %T formatting option. # # %T Treat argument as a date/time string and format it accordingly. # # %(dateformat)T T can be preceded by dateformat, where dateformat is any date format supported # by the date(1) command.