scriptt_mini.sh



Contents


  1. scriptt_mini.sh
    1. Contents
    2. Purpose
    3. Author
    4. License
    5. History
    6. Operating system
    7. Language / type
    8. Script Usage
    9. Details
      1. Script usage help
      2. Parameter handling
      3. Predefined variables
      4. Logging
      5. BuildIn log functionality
      6. Executing commands
      7. BREAK/CTRL-C handling
      8. Housekeeping / Cleanup
      9. Trap Handler
      10. Wrting daemons
      11. The parameter --var
      12. Tracing functions
      13. Verbose mode for specific functions only
      14. DebugShell
      15. Other functions defined
      16. User defined functions
    10. Links
    11. Download



Purpose

scriptt_mini.sh is a minimal template for Kornshell scripts.

scriptt_mini.sh includes only a very small runtime for shell scripts with functionality for logging, housekeeping, trap handling, and trouble shooting / debugging.

scriptt_mini.sh is only a template for a shell script -- without adding your code it does not do any useful things.

Note:

A much more complex script template for shell scripts with various functions is scriptt.sh.

This description is for scriptt_mini.sh version 3.9.0.



Author


Bernd Schemmer

email: Bernd.Schemmer@gmx.de

Homepage: http://bnsmb.de



License

# CDDL HEADER START
#
# The contents of this file and the script are subject to the terms of the
# Common Development and Distribution License, Version 1.0 only
# (the "License").  You may not use this file except in compliance
# with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END




History


Release History
#T# ----------------------------------------------------------------------
#T#
#T# History of the script template
#T#
#T#   28.04.2016 v1.0.0 /bs
#T#     initial release
#T#
#T#   ...
#T#
#T#   08.11.2017 v2.0.0 /bs
#T#     initial public release
#T#
#T#   24.11.2017 v2.1.0 /bs
#T#     added the parameter -T (use tee to save the script output)
#T#     added the function KillProcess
#T#     the script now supports a timeout for each pid to kill at script end
#T#       (see the comments for the function KillProcess)
#T#     the cleanup function now supports parameter for the exit routines
#T#     the cleanup function now supports parameter for the finish routines
#T#     added the variable INSIDE_CLEANUP_ROUTINE
#T#     added the variable INSIDE_FINISH_ROUTINE
#T#     the parameter -t and the DebugShell aliase for tracing now support
#T#       the variable ${.sh.func} if running in ksh93
#T#     the parameter -t and the DebugShell aliase for tracing now add the statements
#T#       typeset __FUNCTION=<function_name> ; ${__DEBUG_CODE};
#T#     to a function if neccessary and "typeset -f" is supported by the shell used
#T#     added the variable ${ENABLE_DEBUG}; if ${ENABLE_DEBUG} is not ${__TRUE} the DebugShell
#T#       and the parameter -D are disabled
#T#     added the variable ${USAGE_HELP}
#T#     added the function show_extended_usage_help
#T#     added the parameter -L / --listfunctions
#T#     Read_APPL_PARAMS_entries rewritten using an array for the RCM entries
#T#
#T#   07.12.2017 v2.1.1 /bs
#T#     the aliase use now only one line
#T#     LogRotate now aborts the script if it can not create backups of the
#T#       existing log file
#T#
#T#   10.12.2017 v2.2.0 /bs
#T#     added the parameter --var, the parameter --var is disabled if the variable
#T#       ${ENABLE_DEBUG} is not ${__TRUE}
#T#
#T#   19.01.2018 v2.2.1 /bs
#T#     the script now uses /var/tmp/${SCRIPTNAME}.$$.STDOUT_STDERR if it can not
#T#     write to the file /var/tmp/${SCRIPTNAME}.STDOUT_STDERR
#T#
#T#   29.01.2018 v2.2.2 /bs
#T#     the script now uses /var/tmp/${SCRIPTNAME}.log.$$ if it can not
#T#     write to the file /var/tmp/${SCRIPTNAME}.log
#T#     the script now uses /var/tmp/${SCRIPTNAME}.STDOUT_STDERR.$$ if it can not
#T#     write to the file /var/tmp/${SCRIPTNAME}.STDOUT_STDERR
#T#
#T#   09.02.2018 v2.2.3 /bs
#T#     added the parameter --appendlog
#T#     added the parameter --noSTDOUTlog
#T#
#T#   10.02.2018 v2.2.4 /bs
#T#     added the parameter --nologrotate
#T#
#T#   14.02.2018 v2.2.5 /bs
#T#     the script now converts the logfile name to a fully qualified name
#T#     in the previous version the script created additional empty logfiles - fixed
#T#
#T#   01.04.2018 v3.0.0 /bs
#T#     the parameter --var can now be used in this format also: --var:<var>=<value>
#T#     the parameter --tracefunc can now be used in this format also: --tracefunc:fn[..,fn]
#T#     the parameter --logfile can now be used in this format also: --logfile:<logfile>
#T#     the script now prints also the template version if the parameter -v and -V are used
#T#     the script now prints also the template history if the parameter "-h -v -v" are used
#T#     the version of the script and the version of the template are now dynamically
#T#       retrieved from the source code of the script while executing the script
#T#     the parameter "-d" overwrote the value of the environment variable PREFIX -- fixed
#T#     added more details to the usage help for the parameter \"-h\"
#T#     added the DebugShell function editfunc
#T#     added the DebugShell function savefunc
#T#     added the DebugShell function restorefunc
#T#     added the DebugShell function clearsavedfunc
#T#     added the DebugShell function savedfuncs
#T#     added the DebugShell function viewsavedfunc
#T#     the function DebugShell now prints the return code of every executed command
#T#     the function DebugShell did not handle "." commands with errors correct - fixed
#T#     set_debug now preserves existing debug definitions if the parameter starts with a "+"
#T#     the output of the DebugShell alias vi#T#   25.07.2018 v3.0.1 /bsew_debug is now more human readable
#T#     the parameter --appendlog now also sets --nologrotate
#T#
#T#   25.07.2018 v3.1.0 /bs
#T#     added the parameter --nocleanup
#T#     added the variables
#T#       NO_EXIT_ROUTINES     # do not execute the exit routines if set to 0
#T#       NO_TEMPFILES_DELETE  # do not delete temporary files if set to 0
#T#       NO_TEMPDIR_DELETE    # do not delete temporary directories if set to 0
#T#       NO_FINISH_ROUTINES   # do not execute the finish routines if set to 0
#T#       NO_KILL_PROCS        # do not kill the processes if set to 0
#T#     renamed the variable KSH_VERSION to __KSH_VERSION because KSH_VERSION is a
#T#       readonly variable in mksh
#T#
#T#   16.08.2018 v3.2.0 /bs
#T#     the default parameter processing now stops if the parameter "--" is found
#T#     added code to umount temporary mount points at script end
#T#     added the variable
#T#       NO_UMOUNT_MOUNTPOINTS # do not umount temporary mount points at script end
#T#     the cleanup function for the house keeping now does nothing in dry-run mode
#T#     added the function switch_to_background to switch the process with the
#T#       script into the background;
#T#       this functionwas tested in Linux (RHEL), Solaris 10, AIX, and MacOS
#T#
#T#   03.11.2018 v3.2.1 /bs
#T#     corrected a minor bug in the cleanup function
#T#     switch_to_background disabled in the DebugShell
#T#     added the variable DEBUG_SHELL_CALLED
#T#     script called the finish functions twice -- fixed
#T#     the script now also evaluates ${..} in help text marked with #U#
#T#         (-> printed with -h -v)
#T#     corrected some spelling errors
#T#
#T#   16.11.2018 v3.2.2 /bs
#T#     added the variable SYSTEMD_IS_USED
#T#     added the alias __getparameter to process parameter with values
#T#
#T#   25.12.2018 v3.2.2 /bs
#T#     LogMsg return ${__TRUE} if the message was not written - fixed
#T#     LogInfo, LogWarning, and LogError now also support the special parameter "-"
#T#       to suppress the date prefix in the message
#T#     Added the variable __SHELL
#T#     Added the function BackupFile
#T#
#T#   14.01.2019 v3.3.0 /bs
#T#     corrected some code using the special variable LINENO because
#T#       the old code did not work on all ksh versions from Solaris 11
#T#     alias __ignoretraps deleted -- that code is not supported by all ksh versions
#T#     added the variable CUR_OS_VERSION
#T#
#T#   26.03.2019 v3.4.0 /bs
#T#     added the function LogMoreInfo
#T#
#T#   19.07.2019 v3.5.0 /bs
#T#     added the parameter --disable_tty_check
#T#     the script now uses a logfile in /tmp if it can not create a logfile in /var/tmp
#T#       if it can also not create a logfile in /tmp no logfile is used
#T#     DEBUG_SHELL_CALLED was not set to ${__TRUE} in DebugShell -- fixed
#T#
#T#   29.08.2019 vß3.6.0 /bs
#T#     the variable FILES_TO_REMOVE was overwritten in the function DebugShell -- fixed
#T#     added the function create_lock_file
#T# 
#T#   25.10.2019 v3.6.1 /bs
#T#     the script now only prints a small usage help if the parameter -h is used
#T#     (use --help to get the long usage help like before)
#T#
#T#   21.11.2019 v3.6.2 /bs
#T#     added the global variables
#T#       RUNNING_ON_A_VIRTUAL_MACHINE
#T#       THIS_IS_A_VMWARE_MACHINE
#T#       SYSTEM_PRODUCT_NAME
#T#       SYSTEM_PRODUCT_VENDOR
#T#       HPYERVISOR_VENDOR
#T#
#T#   05.02.2020 v3.6.3 /bs
#T#     the function get_fqn did not work due to a missing assignment for the variable READLINK -- fixed
#T#     the error messages printed if the script can not write to the logfile are now print to STDERR instead of STDOUT
#T#
#T#   13.02.2020 v3.6.4 /bs
#T#      added the variables STARTTIME_IN_SECONDS amd STARTTIME_IN_HUMAN_READABLE_FORMAT
#T#      added the variables  ENDTIME_IN_SECONDS, and ENDTIME_IN_HUMAN_READABLE_FORMAT
#T#      added the variables  RUNTIME_IN_SECONDS, and RUNTIME_IN_HUMAN_READABLE_FORMAT
#T#      the script now prints the start time, the runtime in seconds and in human readable format, and the return code at script end
#T#
#T#   28.02.2020 v3.6.5 /bs
#T#      added the parameter -o / --overwrite
#T#      added the parameter --nobackups
#T#      added the function read_file_section
#T#      the definition for the variable CUR_SHELL ("$( head -1 "${REAL_SCRIPTNAME}" | cut -f1 -d " " | cut -c3- )" ) got lost -- fixed
#T#
#T#   28.02.2020 v3.6.6 /bs
#T#      create_lock_file improved
#T#
#T#   19.03.2020 v3.6.7 /bs
#T#      removed not neccessary code to check if the log file is writable
#T#
#T#   20.05.2020 v3.6.8 /bs
#T#      switch_to_background did not work in Solaris -- fixed
#T#      switch_to_background now ends with an error if running in an unknown OS
#T#
#T#   29.06.2020 v3.6.9 /bs
#T#      added the variables STDIN_IS_TTY, STDOUT_IS_TTY, STDERR_IS_TTY
#T#      added the variables STDIN_DEVICE, STDOUT_DEVICE, STDERR_DEVICE
#T#      added the variable RUNNING_IN_A_CONSOLE_SESSION
#T#      added the variable STDOUT_IS_A_PIPE
#T#      added the variable STDIN_IS_A_PIPE
#T#      added the variable PARENT_PROCECSS_EXECUTABLE
#T#
#T#   04.07.2020 v3.7.0 /bs
#T#      corrected the code to detect the binary to use for readlink (variable READLINK) again
#T#
#T#   06.07.2020 v3.7.1 /bs
#T#     the new code from 3.6.9 did not work correct if /tmp was mountd with the option noexec -- fixed
#T#
#T#   06.07.2020 v3.7.2 /bs
#T#     code to get STDIN_DEVICE and STDOUT_DEVICE rewritten
#T#
#T#   06.01.2021 v3.8.0 /bs
#T#     the global settings wiill now be printed with LogRuntimeInfo
#T#     changed the code to process the parameter -d
#T#     added support for the dummy parameter "-"
#T#
#T#   14.03.2021 v3.8.1 /bs
#T#     get_fqn now returns the original dir/filename if the directory/file does not exist
#T#
#T#   21.03.2021 v3.8.2 /bs
#T#     the script now prints a hint if the equal sign (=) is used in an unknown parameter
#T#
#T#   25.04.2021 v3.8.3 /bs
#T#     the function show_extended_usage_help (executed if the parameter "-v -h" are used) now
#T#       prints more details for the supported environment variables
#T#     the variables TMPFILE1 and TMPFILE2 were only filled if running under Linux -- fixed
#T#     the variable SED was not defined -- fixed
#T#
#T#   28.04.2021 v3.8.4 /bs
#T#     the code to remove the default temporary files ${TMPFILE1} and ${TMPFILE2} was removed -- fixed
#T#     added the variable NO_OF_LOGFILES_TO_KEEP to define the number of old logfiles to keep
#T#
#T#   18.07.2021 v3.8.5 /bs
#T#     added the function gettime_in_seconds
#T#     added the function runcmd_with_timeout
#T#     the cleanup function will now do the cleanup in this order
#T#       execute all cleanup_functions // kill procs // delete files // umount mount points // delete directories  / execute all finish_functions
#T#     added the parameter --print_runtime_vars
#T#     all cp, mv, and rm commands used are now prefixed with a slash "\" to ignore aliase
#T#
#T#   22.02.2022 v3.8.6 /bs
#T#     removed the not set variable ${THISSCRIPT} from the string in the function LogMsg
#T#
#T#   23.03.2022 v3.8.7 /bs
#T#     added the variable PRINT_COMMAND_TO_EXECUTE : If this variable is true ExecuteCommandAndLog will print all commands before executing them
#T#     minor cosmetic changes only
#T#     The function BackupFile now use the name of the file to backup also for the backup file if the parameter for the backup file name is missing
#T#     added the function convert_variable_to_boolean
#T#     added the function is_variable_true
#T#
#T#   22.04.2022 v3.9.0 /bs
#T#     fixed some typos and errors in the messages
#T#     fixed some minor errors
#T#     added support to enable the verbose mode for specific functions only (parameter "-v:fn")
#T#     lines starting with #h#, #H#, and #U#  can now be mixed in the comments
#T#     the number of log files to keep can now be defined by the prefix ":n" for the value of the parameter "-l"
#T#     to use the default log file and only change the number of logfiles to keep the parameter "-l :n" can be used
#T#     the function gettime_in_seconds now uses "date +%s" if perl is not working
#T#     the alias set_debug in the DebugShell now preserves the value of the variable __DEBUG_CODE









Operating system


Solaris, Linux, AIX, Windows with Cygwin; Darwin (MacOS)

Primary development is done on Linux (Redhat) and Solaris


Language / type


Kornshell Script . Note that not all ksh features required for this script template are available in all kornshell versions. E.g. in the ksh from Solaris 10 some features for the trace handling are missing.

Be aware that the features for the debugging do not work in sh or bash.



Script Usage


Use the parameter -h to get a short usage help:


[xtrnaw7@t15g /data/develop/scripts]$ ./scriptt_mini.sh -h
[23.04.2022 16:49] ### scriptt_mini.sh started at 23.04.2022 16:49:33 (The PID of this process is 3039916)
 Usage:    <scriptname> [-h|--help] [-v|--verbose] [-v:fn|--verbose:fn] [-q|--quiet] [-f|--force] [-o|--overwrite] [-y|--yes] [-n|--no]
               [-l|--logfile [filename[:n]|:n] [-d{:dryrun_prefix}|--dryrun{:dryrun_prefix}] [-D|--debugshell] [-t fn|--tracefunc fn] [-L]
               [-T|--tee] [-V|--version] [--var name=value] [--appendlog] [--nologrotate] [--noSTDOUTlog] [--print_runtime_vars]
               [--nocleanup] [--nobackups] [--disable_tty_check]

 Use the parameter "--help" to print the detailed help message; use the parameter "--help -v" to also print the list of supported environment variables

Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes

[23.04.2022 16:49] ### The logfile used was /var/tmp/scriptt_mini.sh.log
[23.04.2022 16:49] ### The start time was 23.04.2022 16:49:33, the script runtime is (day:hour:minute:seconds) 0:00:00:00 (= 0 seconds)
[23.04.2022 16:49] ### scriptt_mini.sh ended at 23.04.2022 16:49:33 (The PID of this process is 3039916; the RC is 0)
[xtrnaw7@t15g /data/develop/scripts]$

Use the parameter --help to get a detailed usage help:

./scriptt_mini.sh --help
[xtrnaw7@t15g /data/develop/scripts]$ ./scriptt_mini.sh --help
[23.04.2022 16:50] ### scriptt_mini.sh started at 23.04.2022 16:50:05 (The PID of this process is 3040647)
 <scriptname>

 Function: ???
 
 Usage:    <scriptname> [-h|--help] [-v|--verbose] [-v:fn|--verbose:fn] [-q|--quiet] [-f|--force] [-o|--overwrite] [-y|--yes] [-n|--no]
               [-l|--logfile [filename[:n]|:n] [-d{:dryrun_prefix}|--dryrun{:dryrun_prefix}] [-D|--debugshell] [-t fn|--tracefunc fn] [-L]
               [-T|--tee] [-V|--version] [--var name=value] [--appendlog] [--nologrotate] [--noSTDOUTlog] [--print_runtime_vars]
               [--nocleanup] [--nobackups] [--disable_tty_check]

 Parameter:
   -h - print the script usage; use "-h" and "-v" one or more times to print more help text
       
   -v - verbose mode; use "-v" "-v" to also print the runtime system messages
        (or set the environment variables VERBOSE to 0 and VERBOSE_LEVEL to the level)
   -v:fn
        enable verbose mode for the function "fn"; use the comma "," to separate multiple functions
        or use the parameter more than once. The format "-v fn" is NOT supported for this parameter.
   -q - quiet mode (or set the environment variable QUIET to 0)
   -f - force execution (or set the environment variable FORCE to 0 )
   -o - enable overwrite mode (or set the environment variable OVERWRITE to 0 )
   -y - answer yes to all questions
   -n - answer no to all questions
   -l - logfile to use; use "-l none" or "-l -" to not use a logfile at all
        the default logfile is /var/tmp/scriptt_mini.sh.log
        also supported is the format "-l:filename"
        The build-in logrotate will keep 10 versions of the log file
        Use the prefix ":n" for the filename to change the number of logfiles to keep
        Use the syntax "-l :n" or "-l default:n" to use the default logfile and only change the number of logfiles to keep
   -d - dryrun mode, default dryrun_prefix is: "echo  "
        Use the parameter "-d:<dryrun_prefix>" or the syntax
        "PREFIX=<new dryrun_prefix> /data/develop/scripts/scriptt_mini.sh"
        to change the dryrun prefix
        The script will run in dryrun mode if the environment variable PREFIX
        is set. To disable that behaviour use the parameter "+d"
        If the parameter "-d" is used without a value and there are other
        parameter following that do NOT start with a hyphen (-) use the format "-d - [other_parameter]"
        Note: dryrun mode is not supported in this script
       
   -D - start a debug shell and continue the script afterwards
        Note that the debug shell will be executed while processing the parameter; the parameter can be used
        multiple times
       
   -t - trace the function fn; the parameter can be used multiple times.
        also supported is the format "-t:fn[,...,fn#]"
        This functionality does not work for a few internal functions used by the runtime system.
   -L - list all defined functions and end the script
   -T - copy STDOUT and STDERR to the file /var/tmp/scriptt_mini.sh.3040647.tee.log
        using tee; set the environment variable __TEE_OUTPUT_FILE before
        calling the script to change the file used for the output of tee
        Note that you can NOT set the variable __TEE_OUTPUT_FILE using the parameter "--var var=value"
   -V - print the script version and exit; use "-v -V" to print the
        template version also
   --var
      - set the variable "name" to the value "value"
        also supported is the format "--var:<varname>=<value>"
   --appendlog
      - append the messages to the logfile (default: overwrite an existing logfile)
        This parameter also sets "--nologrotate"
   --nologrotate
      - do not create a backup of an existing logfile
   --noSTDOUTlog
      - do not write STDOUT/STDERR to a file if /dev/tty is not a a device
   --nocleanup
      - do no house keeping at script end
   --nobackups
      - do not create backups
   --disable_tty_check
      - disable the check if we do have a tty
   --print_runtime_vars
      - print the runtime variables defined and exit the script

Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes

[23.04.2022 16:50] ### The logfile used was /var/tmp/scriptt_mini.sh.log
[23.04.2022 16:50] ### The start time was 23.04.2022 16:50:05, the script runtime is (day:hour:minute:seconds) 0:00:00:00 (= 0 seconds)
[23.04.2022 16:50] ### scriptt_mini.sh ended at 23.04.2022 16:50:05 (The PID of this process is 3040647; the RC is 0)
[xtrnaw7@t15g /data/develop/scripts]$





Note:

These are "only" the pre-defined parameter. You can add additional parameter, of course.


Use the additional parameter -v multiple times to get more details:

./scriptt_mini.sh -v -v --help
[xtrnaw7@t15g /data/develop/scripts]$ ./scriptt_mini.sh -v -v --help
[23.04.2022 16:50] ### scriptt_mini.sh started at 23.04.2022 16:50:59 (The PID of this process is 3041879)
 <scriptname>

 Function: ???
 
 Usage:    <scriptname> [-h|--help] [-v|--verbose] [-v:fn|--verbose:fn] [-q|--quiet] [-f|--force] [-o|--overwrite] [-y|--yes] [-n|--no]
               [-l|--logfile [filename[:n]|:n] [-d{:dryrun_prefix}|--dryrun{:dryrun_prefix}] [-D|--debugshell] [-t fn|--tracefunc fn] [-L]
               [-T|--tee] [-V|--version] [--var name=value] [--appendlog] [--nologrotate] [--noSTDOUTlog] [--print_runtime_vars]
               [--nocleanup] [--nobackups] [--disable_tty_check]

 Parameter:
   -h - print the script usage; use "-h" and "-v" one or more times to print more help text
       
   -v - verbose mode; use "-v" "-v" to also print the runtime system messages
        (or set the environment variables VERBOSE to 0 and VERBOSE_LEVEL to the level)
   -v:fn
        enable verbose mode for the function "fn"; use the comma "," to separate multiple functions
        or use the parameter more than once. The format "-v fn" is NOT supported for this parameter.
        Note that this only works for functions using the code from the function "function_template"
        Also note that the script will create an alias for return if this parameter is used
   -q - quiet mode (or set the environment variable QUIET to 0)
   -f - force execution (or set the environment variable FORCE to 0 )
   -o - enable overwrite mode (or set the environment variable OVERWRITE to 0 )
   -y - answer yes to all questions
   -n - answer no to all questions
   -l - logfile to use; use "-l none" or "-l -" to not use a logfile at all
        the default logfile is /var/tmp/scriptt_mini.sh.log
        also supported is the format "-l:filename"
        The build-in logrotate will keep 10 versions of the log file
        Use the prefix ":n" for the filename to change the number of logfiles to keep
        Use the syntax "-l :n" or "-l default:n" to use the default logfile and only change the number of logfiles to keep
        Alternative: 
          Set the environment variable NO_OF_LOGFILES_TO_KEEP to change this value either before
          starting the script or using the parameter "--var var=value"
   -d - dryrun mode, default dryrun_prefix is: "echo  "
        Use the parameter "-d:<dryrun_prefix>" or the syntax
        "PREFIX=<new dryrun_prefix> /data/develop/scripts/scriptt_mini.sh"
        to change the dryrun prefix
        The script will run in dryrun mode if the environment variable PREFIX
        is set. To disable that behaviour use the parameter "+d"
        If the parameter "-d" is used without a value and there are other
        parameter following that do NOT start with a hyphen (-) use the format "-d - [other_parameter]"
        Note: dryrun mode is not supported in this script
       
   -D - start a debug shell and continue the script afterwards
        Note that the debug shell will be executed while processing the parameter; the parameter can be used
        multiple times
       
   -t - trace the function fn; the parameter can be used multiple times.
        also supported is the format "-t:fn[,...,fn#]"
        This functionality does not work for a few internal functions used by the runtime system.
   -L - list all defined functions and end the script
   -T - copy STDOUT and STDERR to the file /var/tmp/scriptt_mini.sh.3041879.tee.log
        using tee; set the environment variable __TEE_OUTPUT_FILE before
        calling the script to change the file used for the output of tee
        Note that you can NOT set the variable __TEE_OUTPUT_FILE using the parameter "--var var=value"
   -V - print the script version and exit; use "-v -V" to print the
        template version also
   --var
      - set the variable "name" to the value "value"
        also supported is the format "--var:<varname>=<value>"
   --appendlog
      - append the messages to the logfile (default: overwrite an existing logfile)
        This parameter also sets "--nologrotate"
   --nologrotate
      - do not create a backup of an existing logfile
   --noSTDOUTlog
      - do not write STDOUT/STDERR to a file if /dev/tty is not a a device
   --nocleanup
      - do no house keeping at script end
   --nobackups
      - do not create backups
   --disable_tty_check
      - disable the check if we do have a tty
   --print_runtime_vars
      - print the runtime variables defined and exit the script


 Parameter that toggle a switch from true to false or vice versa can
 be used with the plus sign (+) instead of minus (-) to invert the usage, e.g.
 
 The parameter "-v" enables the verbose mode; the parameter "+v" disables the verbose mode.
 The parameter "--quiet" enables the quiet mode; the parameter "++quiet" disables the quiet mode.

 All parameter are processed in the given order, e.g.

  <scriptname> -v +v
    -> verbose mode is now off

  <scriptname> +v -v
    -> verbose mode is now on

 Parameter are evaluated after the evaluation of environment variables, e.g

 VERBOSE=0  <scriptname>
     -> verbose mode is now on

 VERBOSE=0  <scriptname> +v
     -> verbose mode is now off

 
 To disable one or more of the house keeping tasks you might set some variables
 either before starting the script or via the parameter "--var name=value"
 
 The defined variables are
 
  NO_EXIT_ROUTINES=0       # do not execute the exit routines if set to 0
  NO_TEMPFILES_DELETE=0    # do not delete temporary files if set to 0
  NO_TEMPDIR_DELETE=0      # do not delete temporary directories if set to 0
  NO_FINISH_ROUTINES=0     # do not execute the finish routines if set to 0
  NO_UMOUNT_MOUNTPOINTS=0  # do not umount temporary mount points if set to 0
  NO_KILL_PROCS=0          # do not kill the processes if set to 0
 

Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes


 Supported environment variables are (values for booleans: 0 = TRUE, 1 = FALSE):

 Variable                    Type                                       Current value                              Comment                                           

 PREFIX                      string                                     ""                                         prefix used in dry-run-mode                       
 __DEBUG_CODE                string                                     ""                                         debug code for the functions                      
 __TEE_OUTPUT_FILE           filename                                   "/var/tmp/scriptt_mini.sh.3041879.tee.log" log file used for  --tee                          
 USE_ONLY_KSH88_FEATURES     boolean                                    "1"                                                                                          
 DISABLE_TTY_CHECK           boolean                                    "1"                                        paramaeter disable_tty_check                      
 BREAK_ALLOWED               string                                     "DebugShell"                               0 / 1 / DebugShell                                
 EDITOR                      filename                                   "/usr/bin/nano"                            editor to use                                     
 PAGER                       filename                                   "/usr/bin/less"                            pager to use                                      
 LOGFILE                     filename                                   "/var/tmp/scriptt_mini.sh.log"             log file                                          
 NO_OF_LOGFILES_TO_KEEP      integer                                    "10"                                       number of log files to keep                       
 NOHUP_STDOUT_STDERR_FILE    filename                                   ""                                         log file used in the function switch_to_background

 FORCE                       boolean                                    "1"                                        parameter --force                                 
 QUIET                       boolean                                    "1"                                        parameter --quiet                                 
 VERBOSE                     boolean                                    "0"                                        parameter --verbose                               
 VERBOSE_LEVEL               boolean                                    "2"                                                                                          
 OVERWRITE                   boolean                                    "1"                                        parameter --overwrite                             

# environment variables for the RCM methods

 RCM_SERVICE                 string                                     ""                                         used only in the RCM methods                      
 RCM_FUNCTION                string                                     ""                                         used only in the RCM methods                      
 RCM_USERID                  string                                     ""                                         used only in the RCM methods                      
 RCM_PASSWORD                string                                     ""                                         used only in the RCM methods                      

 How to use the variables:
     
 Either define the environment variables before executing the script or use the parameter "--var name=value"
 

 History: 
   01.04.2018 v1.0.0 /bs
     initial release

[23.04.2022 16:50] ### The logfile used was /var/tmp/scriptt_mini.sh.log
[23.04.2022 16:50] ### The start time was 23.04.2022 16:50:59, the script runtime is (day:hour:minute:seconds) 0:00:00:00 (= 0 seconds)
[23.04.2022 16:50] ### scriptt_mini.sh ended at 23.04.2022 16:50:59 (The PID of this process is 3041879; the RC is 0)
[xtrnaw7@t15g /data/develop/scripts]$



Use the parameter -v -V to get the version of the template:

[xtrnaw7@t15g /data/develop/scripts]$ ./scriptt_mini.sh -v -V
[23.04.2022 16:51] ### scriptt_mini.sh started at 23.04.2022 16:51:40 (The PID of this process is 3042821)
v1.0.0
The Script template version is v3.9.0
[23.04.2022 16:51] ### The start time was 23.04.2022 16:51:40, the script runtime is (day:hour:minute:seconds) 0:00:00:00 (= 0 seconds)
[23.04.2022 16:51] ### scriptt_mini.sh ended at 23.04.2022 16:51:40 (The PID of this process is 3042821; the RC is 0)
[xtrnaw7@t15g /data/develop/scripts]$




Details



Script usage help

If scriptt_mini.sh is called with the parameter -h a short usage help is written to STDOUT; if the parameter --help is used a detailed usage help is written to STDOUT. In both cases the parameter -v can be used one or more times to print more details.

The function used in all cases is show_script_usage.

To avoid redundant information the function show_script_usage reads the source of the script and prints all lines starting with some marker in the first 3 columns of each line (without the marker):


Parameter print lines with the Marker
Used for
-h #h# print the short usage help
--help
#H# and #h#
print the short usage help and the detailed usage help
-h -v #U# and #h#
print the short usage help and the extended usage help
--help -v
#U#, #H# and #h# print the short usage help, the detailed usage help, and the extended usage help
-h -v -v #V#, #U#, and #h# print the short usage help, the extended usage help, and the version history
--help -v -v
#V#, #U#, #H#, and #h# print the short usage help, the detailed usage help, the extended usage help and the version history
-h -v -v -v #T#, #V#, #U# and #h#
print the short usage help, the extended usage help, the version history, and the template version history
--help -v -v -v #T#, #V#, #U#, #H#, and #h# print the short usage help, the detailed usage help, the extended usage help, the version history and the template version history

Lines beginning with #h#, #H#, or #U# can be mixed and will be printed in the given order.
Lines beginning with #T# or #V# will be printed separate.

The function show_script_usage will print the contents of the variable USAGE_HELP to STDOUT if defined.
If the parameter "-v" is used at least once, the function show_script_usage will also execute the function show_extended_usage_help if that function is defined.



Parameter handling


scriptt_mini.sh processes all parameter found and known; the parameter handling stops at the first not known parameter or if the parameter "--" is found.

The remaining parameter will be saved in the global variable NOT_USED_PARAMETER.

For switches that can be set via environment variable and via parameter the parameter will always overwrite the value of the environment variable.

Before processing the parameter the script stores all parameter in the global variable ALL_PARAMETER.

The script defines the alias __getparameter to handle parameter with values like "-l logfile" so that the user can use either "-l logfile" or "-l:logfile" . The alias __getparameter stores the value for the parameter in the variable CUR_VALUE.

Example code:


    -t | --tracefunc | -t:* | --tracefunc:* )
       __getparameter   
      
       if [ "${CUR_VALUE}"x = ""x ] ; then
         LogError "Missing value for -t"
         PARAMETER_OKAY=${__FALSE}
       elif [ "${CUR_VALUE}"x = "none"x ] ; then
         LogInfo "Disabling tracing for all functions"
         FUNCTIONS_TO_TRACE=""
       else
         FUNCTIONS_TO_TRACE="${FUNCTIONS_TO_TRACE} $( echo "${CUR_VALUE}" | tr "," " " )"
       fi
       ;;

    -l | --logfile | -l:* | --logfile:* )

       LOGFILE_PARAMETER_FOUND=${__TRUE}
       __getparameter

       if [ "${CUR_VALUE}"x = ""x ] ; then
         LogInfo "Running without a logfile (no value for the parameter -l found)"
         LOGFILE=""
       elif [[ ${CUR_VALUE} = -* ]] ; then
         LogInfo "Running without a logfile (no value for the parameter -l found)"
         LOGFILE=""
       elif [ "${CUR_VALUE}"x = "none"x ] ; then
         LogInfo "Running without a logfile"
         LOGFILE=""
       else
         LOGFILE="${CUR_VALUE}"
         LogRuntimeInfo "Using the logfile ${LOGFILE}"
       fi
       ;;


 Parameter that toggle a switch from true to false or vice versa can be used with the plus sign (+) instead of minus (-) to invert the usage, e.g.
 
 The parameter "-v" enables the verbose mode; the parameter "+v" disables the verbose mode.

 The parameter "--quiet" enables the quiet mode; the parameter "++quiet" disables the quiet mode.


 All parameter are processed in the given order, e.g.

  <scriptname> -v +v
    -> verbose mode is now off

  <scriptname> +v -v
    -> verbose mode is now on

 Parameter are evaluated after the evaluation of environment variables, e.g

 VERBOSE=0  <scriptname>
     -> verbose mode is now on

 VERBOSE=0  <scriptname> +v
     -> verbose mode is now off



Predefined variables


scriptt_mini.sh defines the following variables:

Notes:

If the value in the column "Environment variable used?" is yes for a variable the script uses the value of the environment variable set before the script starts

Most of the variables are writable but you should only change them if really neccessary.


Variablename
Content
Environment
variable used?
Comment
__TEMPLATE_VERSION
version of the script template

this variable is set dynamically while running the script
SCRIPT_VERSION version of the script
this variable is set dynamically while running the script
__TRUE 0
constant for true
__FALSE 1
constant for false
DEFAULT_DRYRUN_PREFIX default value for PREFIX
the value is "echo"
PREFIX
prefix for executables or commands called by the script to implement the dry-run feature
yes
you must use

${PREFIX} os_command {..}

for all binaries/commands in your script to use the dry-run feature

Note that therefor the dry-run modes is disabled in the default (see DRYRUN_MODE_DISABLED)
__KSH_VERSION
ksh version - either 88 or 93

variable name was KSH_VERSION in previous versions
USE_ONLY_KSH88_FEATURES
${__TRUE} if the ksh is compatible to ksh88 only
yes
the default value depends on the ksh version used to execute the script
TYPESET_F_SUPPORTED
"yes" if the current shell supports "typeset -f function_name" else "no"

some ksh88 shells (like the one in Solaris 10) do not support this feature
TRACE_FEATURE_SUPPORTED
"yes" if the current shell supports $0 in functions else "no"

some ksh88 shells (like the one in Solaris 10) do not support this feature -- see DebugShell for a workaround
__SHELL
name of the current shell executing this script



NOHUP_STDOUT_STDERR_FILE Filename for STDOUT and STDERR if the script is switched into the background using the function switch_to_background yes




ENABLE_DEBUG if ENABLE_DEBUG is not ${__TRUE} the DebugShell and
the parameter -D are disabled

this is useful for example for scripts that can be executed as root user via sudo
__DEBUG_CODE
debug code for the functions -- see Tracing function and DebugShell
yes
you must use eval in the debug code and the debug code should not write to STDOUT, e.g

__DEBUG_CODE="eval echo \"Current function is \$__FUNCTION\" >&2 " ./scriptt_mini.sh

__FUNCTIONS_WITH_DEBUG_CODE function with debug code enabled

__LIST_OF_SAVED_FUNCTIONS list of saved functions via DebugShell alias savefunc

__FUNCTION_INIT
code to execute in every function -- see trap handling


AWK awk binary to use

ID id binary to use

EDITOR editor binary to use with the DebugShell alias editfunc yes default: "which vi"
PAGER pager binary to use with the DebugShell alias viewsavedfunc yes default: "which less" and, if no less found, "which more"
BREAK_ALLOWED
either ${__TRUE}, ${__FALSE}, or DebugShell, Default is DebugShell
yes
${__TRUE} - CTRL-C aborts the script
${__FALSE} - CTRL-C is disabled
DebugShell - call the DebugShell if CTRL-C is pressed
USAGE_HELP additional messages that will be printed if the parameter -v and -h are used

ENV_VARIABLES list of environment variables used

LIST_FUNCTIONS_AND_EXIT
${__TRUE} if the parameter -L is used






STARTTIME_IN_SECONDS
start time of this execution in seconds since 1.1.1970


STARTTIME_IN_HUMAN_READABLE_FORMAT
start time of this execution in the format dd:hh:mm:ss


ENDTIME_IN_SECONDS
end time of this execution in seconds since 1.1.1970
this variable is set in the function die
ENDTIME_IN_HUMAN_READABLE_FORMAT
end time of this execution in the format dd:hh:mm:ss
this variable is set in the function die
RUNTIME_IN_SECONDS
run time of this execution in seconds
this variable is set in the function die
RUNTIME_IN_HUMAN_READABLE_FORMAT
run time of this execution in the format dd:hh:mm:ss
this variable is set in the function die




CUR_HOST
hostname

output of the command "hostname"; so either with or without domain
CUR_SHORT_HOST
hostname without the domain


CUR_OS
Operating system

output of the command "uname -s"
CUR_OS_VERSION
OS version

output of the command "uname -r"
CUR_SHELL current shell used

SYSTEMD_IS_USED
${__TRUE} if systemd is used on this machine else ${__FALSE}


SCRIPTNAME
name of the script as used by the user (e.g. ./myscript.sh, /home/user/myscript.sh)


SCRIPTDIR
directory with the script as used by the user ( e.g.  ./ ,  ../bin/, /usr/local/bin)


REAL_SCRIPTDIR
absolute path for the script (always starting with a /)


REAL_SCRIPTNAME
fully qualified name of the script






WORKING_DIR
current working directory at script start


LOGFILE
log file for the script, default is /var/tmp/<scriptname>.log
yes
use the parameter -l to change the logfile used; use the parameter -l none to not use a logfile
LOGFILE_FOUND
LOG_MESSAGE_CACHE
internal variables for the log file handling -- do not change

The functions to write log messages will store the messages in the variable LOG_MESSAGE_CACHE until the name of the log file to use is fix.
__TEE_OUTPUT_FILE file for the output of STDOUT and STDERR if the parameter -T  is used
yes
default value is /var/tmp/${0##*/}.$$.tee.log
__PPID
internal variable used by the code to implement the parameter -T/--tee

see the source code for details
__MAINRC
internal variable used by the code to implement the parameter -T/--tee
see the source code for details




ALL_PARAMETER all parameter for the script


NOT_USED_PARAMETER the script parameter that are not processed by the runtime code


DRYRUN_MODE_DISABLED
if set to ${__TRUE} : disable the dry  run mode (-> the parameter "-d" will be ignored); set this variable to ${__FALSE} to enable activating the dry run mode via parameter "-d"

the dry run feature is disabled in the default settings because it only works if all external commands are prefixed with  ${__PREFIX}
CUR_USER_ID
UID (e.g. 1000)


CUR_USER_NAME
user name (e.g. max)






CUR_GROUP_ID
GID (e.g. 1000)


CUR_GROUP_NAME
group name (e.g. staff)






RUNNING_IN_TERMINAL_SESSION
${__TRUE} - the script is running in an interactive session; ${__FALSE} - the script is running in a session without a tty

if the parameter --disable_tty_check is used this variable is always ${__TRUE}
DISABLE_TTY_CHECK
${__TRUE} - disable the check for a tty and always assume we do have a tty
yes

DIRS_TO_REMOVE
directories that should be deleted at script end in the cleanup function

FILES_TO_REMOVE
files that should be deleted at script end in the cleanup function

PROCS_TO_KILL
processes that should be killed at script end in the cleanup function

KILL_PROC_TIMEOUT
number of seconds to wait after the "kill <pid>" command in the housekeeping routine until a "kill -9 <pid>" is issued
Use "-1" to disable "kill -9 <pid>".

this is only the default timeout value for all PIDs; you can define a different timeout for each PID in PROCS_TO_KILL using the syntax PID:timeout_in_seconds.
CLEANUP_FUNCTIONS
commands to execute in the cleanup function before doing the other cleanup tasks (e.g.kill processes, remove temporary files and directories, etc)


FINISH_FUNCTIONS
commands to execute in the finish function after doing the other cleanup tasks (e.g.kill processes, remove temporary files and directories, etc)

MOUNTS_TO_UMOUNT temporary mount points to umount in the function cleanup function





APPLICATION_VARIABLES
additional variables to print in the DebugShell


RUNTIME_VARIABLES
variables to print in the DebugShell, see DebugShell






QUIET
${__TRUE} if the parameter -q is used
yes

FORCE
${__TRUE} if the parameter -f is used
yes

VERBOSE
${__TRUE} if the parameter -v is used
yes

VERBOSE_LEVEL
if this variable is greater then 1 the script also prints the runtime messages; use multiple times "-v" to increase the VERBOSE_LEVEL
yes

APPEND_LOG ${__TRUE} if the parameter --appendlog  is used
def. : overwrite an existing logfile
LOG_STDOUT ${__FALSE} if the parameter --noSTDOUTlog is used
if ${__FALSE}: do not write STDOUT/STDERR to a file if STDIN is not a tty
ROTATE_LOG
${__FALSE} if the parameter --nologrotate is used or if the logfile is already rotated


NO_OF_LOGFILES_TO_KEEP
number of logfiles to keep while doing the log rotate
yes

PRINT_COMMAND_TO_EXECUTE
the function executeCommandAndLog will print the command to execute if this variable is ${__TRUE}






__USER_RESPONSE_IS
"y" if parameter -y is used; "n" if parameter -n is used; else empty

if the variable __USER_RESPONSE_IS is either "y" or "n" the function AskUser will use that value and not request input from the user
__NOECHO
variable for the function AskUser: Do not print the user input if set to ${__TRUE}
default is ${__FALSE}
__USE_TTY
variable for the function AskUser: User /dev/tty instead of STDIN or STDOUT if set to ${__TRUE}
default is ${__FALSE}
__DEBUG_SHELL_IN_ASKUSER
variable for the function AskUser: Allow to call the DebugShell  in AskUser if set to ${__TRUE}
default is ${__TRUE}
__STTY_SETTINGS
stty settings; used in the function die to reset the stty settings if neccessary


USER_INPUT
LAST_USER_INPUT
global variables for the user input used in the function AskUser






INSIDE_DIE
${__TRUE} if inside of the function die


INSIDE_DEBUG_SHELL
${__TRUE} if inside of the function DebugShell


INSIDE_CLEANUP_ROUTINE
${__TRUE} if inside of one of the cleanup routines


INSIDE_FINISH_ROUTINE ${__TRUE} if inside of one of the finish routes


INSIDE_USR1_HANDLER
${__TRUE} if inside the trap handler for the signal USR1


INSIDE_USR2_HANDLER ${__TRUE} if inside the trap handler for the signal USR2

INSIDE_BREAK_HANDLER
${__TRUE} if inside the trap handler for the signal BREAK


INSIDE_HUP_HANDLER ${__TRUE} if inside the trap handler for the signal HUP


INSIDE_EXIT_HANDLER ${__TRUE} if inside the trap handler for the signal EXIT


INSIDE_QUIT_HANDLER ${__TRUE} if inside the trap handler for the signal QUIT


DEBUG_SHELL_CALLED
${__TRUE} if the debug shell was executed at least one time

the runtime system will never reset this variable to ${__FALSE} again




NO_CLEANUP do not any house keeping at script end if set to ${__TRUE}

NO_EXIT_ROUTINES do not execute the exit routines if set to ${__TRUE}


NO_TEMPFILES_DELETE do not delete temporary files if set to ${__TRUE}

NO_TEMPDIR_DELETE do not delete temporary directories if set to ${__TRUE}

NO_FINISH_ROUTINES do not execute the finish routines if set to ${__TRUE}

NO_KILL_PROCS do not kill the processes if set to ${__TRUE}

NO_UMOUNT_MOUNTPOINTS
do not umount temporary mount points if set to ${__TRUE}





RUNNING_ON_A_VIRTUAL_MACHINE
${__TRUE} if the script is running in a virtual machine


THIS_IS_A_VMWARE_MACHINE
${__TRUE} if the script is running in a VMWare virtual machine

SYSTEM_PRODUCT_NAME

content of /sys/class/dmi/id/product_name


SYSTEM_PRODUCT_VENDOR
content of /sys/class/dmi/id/sys_vendor


HPYERVISOR_VENDOR
VMware, VirtualBox, qemu, or an empty string if running on a physical machine






RCM_SERVICE
RCM_FUNCTION
RCM_HOSTID_FILE
RCM_HOSTID
RCM_DBQUERY
RCM_DBGET_FILE
RCM_USERID
RCM_PASSWORD
FOUND_APPL_PARAM_ENTRY_KEYS
RCM_APPL_PARAMS_KEY
RCM_APPL_PARAMS_VAL
variables used for an RCM environment - - just ignore or delete them if not used








Logging


You should only use one of the defined logging functions to write messages to STDOUT or STDERR. The log function will also write the messages to the logfile and implement a logrotate for the logfile used (with up to n backups; n is the current value of the variable NO_OF_LOGFILES_TO_KEEP; the default value for NO_OF_LOGFILES_TO_KEEP is 10).

To change the number of log files to keep either set the variable NO_OF_LOGFILES_TO_KEEP before calling the script or add the prefix :n to the name of the logfile for the parameter -l, example:

To use the logfile /var/tmp/mylogfile.out and keep 3 old log files use the parameter -l like this:

-l /var/tmp/mylogfile.out:3

To log to the default log file and only change the number of log files to keep use the parameter -l like this

-l :n


Example:

To use the default logfile and keep 5 old log files use one of these parameters:

-l :5
-l::5
-l:default:5


Set the variable ROTATE_LOG to ${__FALSE} or use the parameter --nologrotate to disable the log rotating before calling one of the log functions.

To disable the usage of a logfile set the variable LOGFILE to an empty string or use the parameter -l none.

The default log file is /var/tmp/${SCRIPTNAME}.log. If the script can not write to that log file it uses the log file /var/tmp/${SCRIPTNAME}.log.$$.

Use the parameter --appendlog to extend an existing logfile; in the default the script will always create a new log file.


The defined functions for logging are

Function
Purpose
Comment
LogMsg
write a message to STDOUT and also to the logfile

LogOnly
write a message only to the logfile
LogMsg is used to write the message
LogInfo
write the message prefixed with "INFO: " to STDERR and the logfile if VERBOSE is ${__TRUE} LogMsg is used to write the message
LogError
write the message prefixed with "ERROR: " to STDERR and the logfile
LogMsg is used to write the message
LogWarning
write the message prefixed with "WARNING: " to STDOUT and the logfile
LogMsg is used to write the message
LogMoreInfo
write a message prefixed with "INFO:" to STDERR and the logfile if the variable VERBOSE is ${__TRUE} and if the variable QUIET is not ${__TRUE}

LogRuntimeInfo
internal function to print the verbose messages of the runtime system to STDERR and the logfile
LogMsg is used to write the message



RotateLog
Rotate a file; used for the log rotate
You can use this function to rotate any file, the usage is

RotateLog [file1 [... [file#]]]

The function will keep NO_OF_LOGFILES_TO_KEEP old log files.







BuildIn log functionality


If scriptt_mini.sh is called in a session without an tty all output for STDOUT or STDERR is redirected to the file /var/tmp/${SCRIPTNAME}.STDOUT_STDERR. If the script can not write to that file it uses the file /var/tmp/${SCRIPTNAME}.STDOUT_STDERR.$$ for STDOUT and STDERR. To disable this feature use the parameter --noSTDOUTlog. The parameters -q and --disable_tty_check also disable this feature.

There is also a builtin tee functionality : If the script is called with the parameter -T all output to STDOUT and STDERR from the script and all executed commands will be copied to the file /var/tmp/${0##*/}.$$.tee.log.


Executing commands


scriptt_mini.sh
supports a simple dry-run feature: In dry-run mode every command is prefixed with ${PREFIX}; the default value for the variable PREFIX is  "echo ".

To use the dry-run feature of the script for your commands also use always

    ${PREFIX} os_command {...}

for all commands used in your script that might change something.  "${PREFIX}" is empty in non-dryrun mode; in dry-run mode it is set to "echo " (or what ever you define with the parameter -d).

Note:

In the default settings activating the dry run mode via parameter is disabled beacuse the variable DRYRUN_MODE_DISABLED is set to ${__TRUE}; to enable activating the dry run mode set the variable DRYRUN_MODE_DISABLED to ${__FALSE} in the script.


To execute a command and write all output of the command to STDOUT/STDERR also to the logfile use

    executeCommandAndLog ${PREFIX} os_command {...}


The returncode of executeCommandAndLog is the returncode of the command executed.


For simple and fast commands you can also use code like this

CUR_OUTPUT="$( <your_command> 2>&1 )"
TEMPRC=$?

LogMsg "-" "${CUR_OUTPUT}"

if [ ${TEMPRC} = 0 ]  then
  echo "command was sucessfull"
else
  echo "command was not sucessfull"
fi

There is also a function to execute a command (either an external executable or an internal function) with a timeout: runcmd_with_timeout :

# ----------------------------------------------------------------------
# runcmd_with_timeout
#
# function: run a function or command with timeout
#
# usage: runcmd_with_timeout [timeout_value] [kill_signal] [cmd] [parameter]
#
# returns:
#
#   the return code of the function is the return code of the program executed but only if the program finished before hitting the timeout.
#   If the program is killed by the timeout function the return code of the function is 249.
#   If the first parameter of the function is invalid the function ends with the return code 248
#
# parameter:
#
#   timeout_value
#     timeout value in seconds, use #m for minutes, #h for hours, or (optional) #s for seconds
#
#   kill_signal
#     use "kill -${kill_signal}" to kill the program when the timeout is reached ("kill -9" is neccessary for example for some shell scripts)
#     default is kill with the standard signal to kill a process (which is 15)
#     kill_signal must be a number
#
#   cmd
#     command to execute; the command can NOT be a number
#     "cmd" can be an external command or a function in the script
#
#   parameter
#     parameter for the command to execute
#
# Be carefull with writing messages to STDOUT/STDERR or into the logfile of this script.
#
# Note:
#
# The function does NOT work in AIX
#
# Credits for this function
#    https://stackoverflow.com/questions/24412721/elegant-solution-to-implement-timeout-for-bash-commands-and-functions


Note:

The OS command timeout is not available in all supported OS.



BREAK/CTRL-C handling


scriptt_mini.sh
installs a trap handler for CTRL-C . To disable CTRL-C set the variable BREAK_ALLOWED to ${__FALSE}; to enable CTRL-C set the variable BREAK_ALLOWED to ${__TRUE};  to call the DebugShell if CTRL-C is pressed set the variable BREAK_ALLOWED to DebugShell.

Default value for BREAK_ALLOWED is "DebugShell".


Housekeeping / Cleanup


To do the house keeping at script end you should always use the function die to end the script.

The usage for the function die is

die [script_return_code] [message_to_print]

The default for the parameter script_return_code is 0; there is no default for the parameter message_to_print.

The function die uses the function cleanup to do the house keeping. cleanup does these tasks in this order:

  1.    execute the functions listed in the variable CLEANUP_FUNCTIONS
  2.    kill all running processes listed in the variable PROCS_TO_KILL using "kill" and, if neccessary and enabled, "kill -9"
  3.    delete all files listed in the variable FILES_TO_REMOVE using "rm -f"
  4.    umount all mount points listed in the variable MOUNTS_TO_UMOUNT
  5.    delete all directories listed in the variable DIRS_TO_REMOVE using "rm -rf"
  6.    execute the functions listed in the variable FINISH_FUNCTIONS

scriptt_mini.sh installs a trap handler for the signal EXIT to do the house keeping at script end even if the function die was not used to end the script.


To configure the house keeping for your script do:


To execute a function at script end before the other housekeeping steps are done use

      CLEANUP_FUNCTIONS="${CLEANUP_FUNCTIONS} <your_cleanup_function>"

The number of cleanup functions is not limited; to use parameter for the function use a colon as separator (blanks are not allowed), e.g.

      CLEANUP_FUNCTIONS="${CLEANUP_FUNCTIONS} myfunction:myparameter1:myparameter2:myparameter3"


To start a process in the background that should be killed at script end if it's still running use

    <start_process> &
    ps -p $! >/dev/null && PROCS_TO_KILL="${PROCS_TO_KILL} $!"

The cleanup function waits up to KILL_PROC_TIMEOUT seconds after the kill command to check if kill was sucessfull. If the kill command was not sucessfull the script uses "kill -9" to kill the process.

To change the timeout value for a process use

    PROCS_TO_KILL="${PROCS_TO_KILL} <process_to_kill:timeout_for_this_process>"

To disable the "kill -9" for a process use

    PROCS_TO_KILL="${PROCS_TO_KILL} <process_to_kill:-1>"


To create a file that should be removed at script end if it still exists use

    touch "${NEW_FILE}" && FILES_TO_REMOVE="${FILES_TO_REMOVE} ${NEW_FILE}"


To umount a temporary mount point at script end if it's still mounted use

   TEMP_MOUNTPOINT="<temporary_mount_point>"

    NFS_SHARE="<nfs share>"

    mkdir -p "${TEMP_MOUNTPOINT}"  && DIRS_TO_REMOVE="${DIRS_TO_REMOVE} ${TEMP_MOUNTPOINT}" && \

        mount "${NFS_SHARE}"  "${TEMP_MOUNTPOINT}"  && MOUNTS_TO_UMOUNT="${MOUNTS_TO_UMOUNT} ${TEMP_MOUNTPOINT}"


To create a directory that should be removed at script end if it still exists use

    mkdir -p "${NEW_DIR}" && DIRS_TO_REMOVE="${DIRS_TO_REMOVE} ${NEW_DIR}"


To execute a function at script end after the other housekeeping steps are done use

      FINISH_FUNCTIONS="${FINISH_FUNCTIONS} <your_finish_function>"

The number of finish functions is not limited; to use parameter for the function use a colon as separator (blanks are not allowed), e.g.

      FINISH_FUNCTIONS="${FINISH_FUNCTIONS} myfunction:myparameter1:myparameter2:myparameter3"


To disable the house keeping at script end use the parameter --nocleanup; to only disable one or more house keeping steps set the approbiate variable from the list below to true (= 0 ) either in the script or using the parameter "--var varname=0".

    NO_EXIT_ROUTINES       # do not execute the exit routines if set to 0
    NO_TEMPFILES_DELETE    # do not delete temporary files if set to 0
    NO_TEMPDIR_DELETE      # do not delete temporary directories if set to 0
    NO_FINISH_ROUTINES     # do not execute the finish routines if set to 0
    NO_UMOUNT_MOUNTPOINTS  # do not umount temporary mountpoints if set to 0
    NO_KILL_PROCS          # do not kill the processes if set to 0 NO


 


Trap Handler


scriptt_mini.sh installs the following trap handler for the signals

Signal
Trap Handler
Comment
EXIT
signal_exit_handler
house keeping cleanup
BREAK signal_break_handler
disable or enable CTRL-C
USR1 signal_usr1_handler
call the DebugShell
USR2
signal_usr2_handler the handler does nothing in the default config
HUP
signal_hup_handler the handler does nothing in the default config
QUIT
signal_quit_handler
house keeping cleanup

Unfortunately the trap handler are set back to the default values in each function. Therefor you must set the trap handler in every function.

scriptt_mini.sh defines a few aliases and variables for easier use:

# alias to install the trap handler
#
# Note: The statement LINENO=${LINENO} is necessary to use the variable LINENO in the trap command
#       USR1 and USR2 are different values in the various Unix OS!
#

#  Number   KSH name    Comments
#  0        EXIT        This number does not correspond to a real signal, but the corresponding trap is executed before script termination.
#  1        HUP         hangup
#  2        INT         The interrupt signal typically is generated using the DEL or the ^C key
#  3        QUIT        The quit signal is typically generated using the ^[ key. It is used like the INT signal but explicitly requests a core dump.
#  9        KILL        cannot be caught or ignored
#  10       BUS         bus error
#  11       SEGV        segmentation violation
#  13       PIPE        generated if there is a pipeline without reader to terminate the writing process(es)
#  15       TERM        generated to terminate the process gracefully
#  16       USR1        user defined signal 1, this value is different in other Unix OS!
#  17       USR2        user defined signal 2, this value is different in other Unix OS!
#  -        DEBUG       KSH only: This is no signal, but the corresponding trap code is executed before each statement of the script.
#
alias __settraps="
  LINENO=\${LINENO} ;\
  trap 'signal_hup_handler    \${LINENO}' 1 ;\
  trap 'signal_break_handler  \${LINENO}' 2 ;\
  trap 'signal_quit_handler   \${LINENO}' 3 ;\
  trap 'signal_exit_handler   \${LINENO}' 15 ;\
  trap 'signal_usr1_handler   \${LINENO}' USR1 ;\
  trap 'signal_usr2_handler   \${LINENO}' USR2  ;\
"


# alias to reset all traps to the defaults
#
alias __unsettraps="
  LINENO=\${LINENO} ;\
  trap - 1 ;\
  trap - 2 ;\
  trap - 3 ;\
  trap - 15 ;\
  trap - USR1 ;\
  trap - USR2 ;\
"

__FUNCTION_INIT="eval __settraps"



So every function should start with


function <your_function_name> {
  typeset __FUNCTION="RotateLog"
  ${__DEBUG_CODE}
  ${__FUNCTION_INIT}
...


Note:


The variables __FUNCTION and __DEBUG_CODE are used for other functionalities of the script template


Wrting daemons


To start a script based on scriptt_mini.sh as daemon just use nohup and/or a traling &, e.g.

nohup  /your_scriptt.sh &


Another method to use the script as daemon is the function switch_to_background: The function switch_to_background will redirect STDOUT and STDERR to a file and switch the current process running the script into the background.

Sample code to use this function:

SEMFILE="/tmp/stop"

echo "The PID of this process is $$"
ps -ef | grep $$

  switch_to_background
  LogMsg "Now running in the background ..."

while [ ! -r ${SEMFILE} ] ; do
  echo "$( date ) : ${SCRIPTNAME}; PID $$ is still running ; the semaphor file to stop the script is  ${SEMFILE} "
  echo " This messages goes to STDERR" >&2
  sleep 1
done

Sample output :

[root@t540p /data/develop/scripts]$ ./scriptt_mini.sh
[16.08.2018 15:57 ] ### scriptt_mini.sh started at Thu Aug 16 15:57:01 CEST 2018
[16.08.2018 15:57 ] ### The logfile used is /var/tmp/scriptt_mini.sh.log
[16.08.2018 15:57 ] Hello World, you must add your own code here to do something useful
The PID of this process is 23907
root     23907  4173  0 15:57 pts/7    00:00:00 /bin/ksh ./scriptt_mini.sh
root     23948 23907  0 15:57 pts/7    00:00:00 ps -ef
root     23949 23907  0 15:57 pts/7    00:00:00 grep 23907
[16.08.2018 15:57 ] Switching the process for the script "scriptt_mini.sh" with the PID 23907 into the background now ...
[16.08.2018 15:57 ] STDOUT/STDERR now goes to the file "/data/develop/scripts/nohup.out"

[1]+  Stopped                 ./scriptt_mini.sh
[root@t540p /data/develop/scripts]$
[16.08.2018 15:57 ] *** The script "scriptt_mini.sh" (PID is 23907) should now run in the background ...


[root@t540p /data/develop/scripts]$ tail -f /data/develop/scripts/nohup.out
Thu Aug 16 15:57:08 CEST 2018 : scriptt_mini.sh; PID 23907 is still running ; the semaphor file to stop the script is  /tmp/stop
 This messages goes to STDERR
Thu Aug 16 15:57:09 CEST 2018 : scriptt_mini.sh; PID 23907 is still running ; the semaphor file to stop the script is  /tmp/stop
 This messages goes to STDERR
Thu Aug 16 15:57:10 CEST 2018 : scriptt_mini.sh; PID 23907 is still running ; the semaphor file to stop the script is  /tmp/stop
 This messages goes to STDERR
Thu Aug 16 15:57:11 CEST 2018 : scriptt_mini.sh; PID 23907 is still running ; the semaphor file to stop the script is  /tmp/stop
 This messages goes to STDERR
Thu Aug 16 15:57:12 CEST 2018 : scriptt_mini.sh; PID 23907 is still running ; the semaphor file to stop the script is  /tmp/stop
 This messages goes to STDERR
Thu Aug 16 15:57:13 CEST 2018 : scriptt_mini.sh; PID 23907 is still running ; the semaphor file to stop the script is  /tmp/stop
 This messages goes to STDERR
Thu Aug 16 15:57:14 CEST 2018 : scriptt_mini.sh; PID 23907 is still running ; the semaphor file to stop the script is  /tmp/stop
 This messages goes to STDERR
Thu Aug 16 15:57:15 CEST 2018 : scriptt_mini.sh; PID 23907 is still running ; the semaphor file to stop the script is  /tmp/stop
 This messages goes to STDERR
^C
[root@t540p /data/develop/scripts]$


The function switch_to_background does the same as a key combination CTRL-Z with a "bg" afterwards. Therefor you can switch the process back into the foreground with the command "fg" but only in the session in which the script was executed. Be aware that switching the process into the foreground again will not change the output of STDOUT and STDERR back to the tty of the session.

Use the environment variable NOHUP_STDOUT_STDERR_FILE to change the name of the file used for STDOUT and STDERR in the background process.

Note:  The function switch_to_background will not redirect STDOUT if called with the parameter no_redirect; the function does not redirect or close STDIN.

The function switch_to_background was tested in RHEL, Solaris 10, AIX, and MacOS (Darwin).



The parameter --var


The parameter --var can be used to change the value of a variable, e.g.:

To simulate the parameter -v -v you can use

[xtrnaw7@t540p /data/develop/scripts]$ ./scriptt_mini.sh --var VERBOSE=0 --var VERBOSE_LEVEL=2
[10.12.2017 13:12 ] ### scriptt_mini.sh started at Sun Dec 10 13:12:22 CET 2017
[10.12.2017 13:12 ] Found --VAR parameter for VERBOSE="0"
[10.12.2017 13:12 ] Current value of VERBOSE is: "1"
[10.12.2017 13:12 ] New value of VERBOSE is now: "0"
[10.12.2017 13:12 ] Found --VAR parameter for VERBOSE_LEVEL="2"
[10.12.2017 13:12 ] Current value of VERBOSE_LEVEL is: "0"
[10.12.2017 13:12 ] New value of VERBOSE_LEVEL is now: "2"
[10.12.2017 13:12 ] ### The logfile used is /var/tmp/scriptt_mini.sh.log
[10.12.2017 13:12 ] Hello World, you must add your own code here to do something useful
[10.12.2017 13:12 ] INFO: Housekeeping process started ....
[10.12.2017 13:12 ] INFO: No cleanup functions defined.
[10.12.2017 13:12 ] INFO: No processes to kill defined.
[10.12.2017 13:12 ] INFO: No files to delete defined
[10.12.2017 13:12 ] INFO: No directories to remove defined.
[10.12.2017 13:12 ] INFO: No finish functions to executed defined.
[10.12.2017 13:12 ] ### The logfile used was /var/tmp/scriptt_mini.sh.log
[10.12.2017 13:12 ] ### scriptt_mini.sh ended at Sun Dec 10 13:12:22 CET 2017
[xtrnaw7@t540p /data/develop/scripts]$


To disable deleting files and killing of still running processes at the end of the script use:

[root@t540p /data/develop/scripts]# ./scriptt_mini.sh -v -v --var NO_KILL_PROCS=0 --var:NO_TEMPFILES_DELETE=0
[12.08.2018 12:02 ] ### scriptt_mini.sh started at Sun Aug 12 12:02:30 CEST 2018
[12.08.2018 12:02 ] Found --VAR parameter for NO_KILL_PROCS="0"
[12.08.2018 12:02 ] Current value of NO_KILL_PROCS is: ""
[12.08.2018 12:02 ] New value of NO_KILL_PROCS is now: "0"
[12.08.2018 12:02 ] Found --VAR parameter for NO_TEMPFILES_DELETE="0"
[12.08.2018 12:02 ] Current value of NO_TEMPFILES_DELETE is: ""
[12.08.2018 12:02 ] New value of NO_TEMPFILES_DELETE is now: "0"
[12.08.2018 12:02 ] ### The logfile used is /var/tmp/scriptt_mini.sh.log
[12.08.2018 12:02 ] Hello World, you must add your own code here to do something useful
[12.08.2018 12:02 ] INFO: This is an info message
[12.08.2018 12:02 ] INFO: Housekeeping process started ....
[12.08.2018 12:02 ] INFO: No cleanup functions defined or cleanup functions disabled
[12.08.2018 12:02 ] INFO: No processes to kill defined or process killing disabled
[12.08.2018 12:02 ] INFO: No files to delete defined or files deleting disabled
[12.08.2018 12:02 ] INFO: No directories to remove defined or directory removing disabled
[12.08.2018 12:02 ] INFO: Umounting the mount points to umount "" ...
[12.08.2018 12:02 ] INFO: No finish functions defined or finish functions disabled
[12.08.2018 12:02 ] ### The logfile used was /var/tmp/scriptt_mini.sh.log
[12.08.2018 12:02 ] ### scriptt_mini.sh ended at Sun Aug 12 12:02:30 CEST 2018
[root@t540p /data/develop/scripts]#



Tracing functions


To trace one or more functions the parameter "-t fn" can be used. Tracing is implemented with the variable __DEBUG_CODE. So for this feature the function should be defined like this


function <your_function_name> {
  ${__DEBUG_CODE}
  ${__FUNCTION_INIT}

...

}


The code in __DEBUG_CODE. checks $0 and the local variable __FUNCTION for the name of the function . Unfortunately $0 in functions is not supported by all ksh implementations. Therefor you should start each function like this:

function <your_function_name> {
  typeset __FUNCTION="<function_name>"
  ${__DEBUG_CODE}
  ${__FUNCTION_INIT...

If running in a ksh93 compatible shell the variable $.sh.func is also supported by the debug code and the variable __FUNCTION is optional.

The code in __DEBUG_CODE looks like this 

for ksh88 compatible shells:

eval [ 0 = 1  -o "$0"x = "MyFunction"x -o "${__FUNCTION}"x = "MyFunction"x  -o "$0"x = "MyFunction1"x -o "${__FUNCTION}"x = "MyFunction1"x  ] && printf "
*** Enabling trace for the function ${__FUNCTION:=$0} ...
" >&2 && set -x

and for ksh93 compatible shells:

eval __FUNCTION="${.sh.fun}" ; [ 0 = 1  -o "$0"x = "MyFunction"x -o "${__FUNCTION}"x = "MyFunction"x  -o "$0"x = "MyFunction1"x -o "${__FUNCTION}"x = "MyFunction1"x  ] && printf "
*** Enabling trace for the function ${__FUNCTION:=$0} ...
" >&2 && set -x


If a function that should be traced does not start with "${__DEBUG_CODE}" and the shell used supports dynamic changing the code for a function the script will temporary add the statements

    typeset __FUNCTION=<function_name>; ${__DEBUG_CODE}

to the function and document this with the log message

Adding debug code to the function "<function_name>"


Changing a function dynamically works with some ksh versions but not all. The script will print the status "change function code supported: no" in the usage help and in the DebugShell if this feature is not supported by the current shell. Some ksh versions do not support the usage of $0 in functions. The script prints the status of this feature also if called with the parameter -h and in the DebugShell.

e.g.

[xtrnaw7@t540p /data/develop/scripts]$ ./scriptt_mini.sh -h | grep environment
Current environment: ksh version: 93 | change function code supported: no | tracing feature using $0 supported: no
[xtrnaw7@t540p /data/develop/scripts]$

and in the DebugShell

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: no | tracing feature using $0 supported: no
>>


Note: All functions of the runtime system are already prepared for this workarounds for shells that do not support $0 and therefor already start with "${__DEBUG_CODE}".


Example for the parameter "-t fn" for shells that support $0 in functions
[xtrnaw7@t540p /data/develop/scripts]$ ./scriptt_mini.sh  -v -t MyFunction,Myfunction1,MyFunction1 -t die
[04.11.2017 17:44 ] ### scriptt_mini.sh started at Sat Nov  4 17:44:29 CET 2017
[04.11.2017 17:44 ] ### The logfile used is /var/tmp/scriptt_mini.sh.log
[04.11.2017 17:44 ] Enabling trace for the function "MyFunction" ...
[04.11.2017 17:44 ] Enabling trace for the function "Myfunction1" ...
[04.11.2017 17:44 ] The function "Myfunction1" is not defined
[04.11.2017 17:44 ] Enabling trace for the function "MyFunction1" ...
[04.11.2017 17:44 ] Adding debug code to the function "MyFunction1" ...
[04.11.2017 17:44 ] Enabling trace for the function "die" ...
[04.11.2017 17:44 ] Hello World, you must add your own code here to do something useful

*** Enabling trace for the function MyFunction ...
+ THISRC=0
+ typeset THISRC
+ NO_OF_LINES=0
+ typeset NO_OF_LINES
+ LINENO=1410
+ typeset LINENO
+ CUR_VAR=''
+ typeset CUR_VAR
+ LogMsg 'This is a test function'
[04.11.2017 17:44 ] This is a test function
+ date $'+DATE=%Y-%m-%d\n               YEAR=%Y\n               MONTH=%m\n               DAY=%d\n               TIME=%H:%M:%S\n               HOUR=%H\n               MINUTE=%M\n               SECOND=%S\n               datestamp=%Y-%m-%d_%H.%M.%S\n               DayOfWeek=%a\n               MonthAbbrev=%b'
+ eval DATE=$'2017-11-04\n               YEAR=2017\n               MONTH=11\n               DAY=04\n               TIME=17:44:29\n               HOUR=17\n               MINUTE=44\n               SECOND=29\n               datestamp=2017-11-04_17.44.29\n               DayOfWeek=Sat\n               MonthAbbrev=Nov'
+ DATE=2017-11-04
+ YEAR=2017
+ MONTH=11
+ DAY=04
+ TIME=17:44:29
+ HOUR=17
+ MINUTE=44
+ SECOND=29
+ datestamp=2017-11-04_17.44.29
+ DayOfWeek=Sat
+ MonthAbbrev=Nov
+ eval echo 'YEAR is $YEAR'
+ echo YEAR is 2017
YEAR is 2017
+ eval echo 'MONTH is $MONTH'
+ echo MONTH is 11
MONTH is 11
+ eval echo 'DAY is $DAY'
+ echo DAY is 04
DAY is 04
+ eval echo 'TIME is $TIME'
+ echo TIME is 17:44:29
TIME is 17:44:29
+ eval echo 'HOUR is $HOUR'
+ echo HOUR is 17
HOUR is 17
+ eval echo 'MINUTE is $MINUTE'
+ echo MINUTE is 44
MINUTE is 44
+ eval echo 'SECOND is $SECOND'333
+ echo SECOND is 29
SECOND is 29
+ eval echo 'datestamp is $datestamp'
+ echo datestamp is 2017-11-04_17.44.29
datestamp is 2017-11-04_17.44.29
+ eval echo 'DayOfWeek is $DayOfWeek'
+ echo DayOfWeek is Sat
DayOfWeek is Sat
+ eval echo 'MonthAbbrev is $MonthAbbrev'
+ echo MonthAbbrev is Nov
MonthAbbrev is Nov
+ [ -r /data/develop/scripts/scriptt_mini.sh ]
+ wc -l /data/develop/scripts/scriptt_mini.sh
+ NO_OF_LINES='1686 /data/develop/scripts/scriptt_mini.sh'
+ LogMsg '/data/develop/scripts/scriptt_mini.sh has 1686 /data/develop/scripts/scriptt_mini.sh lines'
[04.11.2017 17:44 ] /data/develop/scripts/scriptt_mini.sh has 1686 /data/develop/scripts/scriptt_mini.sh lines
+ THISRC=0
+ return 0

*** Enabling trace for the function MyFunction1 ...
+ THISRC=0
+ typeset THISRC
+ LogMsg 'Inside of MyFunction1'
[04.11.2017 17:44 ] Inside of MyFunction1
+ return 0

*** Enabling trace for the function die ...
+ THISRC=0
+ typeset THISRC
+ [ 0x '=' x ]
+ INSIDE_DIE=0
+ trap '' EXIT
+ trap '' SIGUSR1
+ trap '' SIGUSR2
+ trap '' SIGINT
+ trap '' SIGHUP
+ [ x '!=' x ]
+ cleanup
+ [ 1 -ne 0 ]
+ shift
+ [ 0 -ne 0 ]
+ [ /var/tmp/scriptt_mini.sh.logx '!=' x -a -f /var/tmp/scriptt_mini.sh.log ]
+ LogMsg '### The logfile used was /var/tmp/scriptt_mini.sh.log'
[04.11.2017 17:44 ] ### The logfile used was /var/tmp/scriptt_mini.sh.log
+ date
+ LogMsg '### scriptt_mini.sh ended at Sat Nov  4 17:44:29 CET 2017'
[04.11.2017 17:44 ] ### scriptt_mini.sh ended at Sat Nov  4 17:44:29 CET 2017
+ exit 0
[xtrnaw7@t540p /data/develop/scripts]$
 



Verbose mode for specific functions only


The parameter -v will enable the verbose mode for the complete script. To enable verbose mode only for some function use

-v:fn

e.g. to enable verbose mode for the functions myfunc1 and myfunc2 use either

-v:myfunc1,myfunc2

or

-v:myfunc1 -v myfunc2

Verbose mode for specific functions is also implemented via the variable __DEBUG_CODE (see Tracing functions) . In addition the script will create an alias for return to restore the original setting for the verbose mode at function end. If this is not usable for a function use either a leading slash \return or "return" (with the double-quotes) to end a function.

Note that the parameter -t an -v:fn can be used in parallel.



DebugShell


The DebugShell is in principle only a loop that reads a line from the user and executes it. DebugShell reads and writes to /dev/tty so you can also use it with STDOUT redirection of your script.

DebugShell is disabled if STDIN is not a tty. To call a DebugShell before starting the script use the parameter -D; to view the online help for the DebugShell menu use "help":


[xtrnaw7@t540p /data/develop/scripts]$ ./scriptt_mini.sh -D
[03.03.2018 09:20 ] ### scriptt_mini.sh started at Sat Mar  3 09:20:09 CET 2018

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> help

vars                      - print the runtime variable values

functions | funcs         - list all defined functions
functions fn | funcs fn   - list functions matching the regex fn

func fn                   - view the source code for the function fn (supported by this shell: yes)
savedfuncs                - list the saved functions (supported by this shell: yes)
editfunc fn               - edit the source code for the function fn (supported by this shell: yes)
savefunc fn               - save the source code of the function fn (supported by this shell: yes)
viewsavedfunc fn          - view the source code of the saved function fn (supported by this shell: yes)
restorefunc fn            - restore the source code of the function fn (supported by this shell: yes)
clearsavedfunc fn         - delete the saved source code of the function fn (supported by this shell: yes)

verbose                   - toggle the verbose switch (Current value: 0)

view_debug                - view the current trace settings
clear_debug               - clear the tracing for all functions
set_debug fn              - enable tracing for the functions fn; use "+fn" to preserve existing settings
add_debug_code fn         - enable debug code for the functions fn (supported by this shell: yes)

exit                      - exit the debug shell
quit                      - end the script using die
abort                     - abort the script using kill -9

!<code>                   - execute the instructions "<code>"
<code>                    - execute the instructions using "eval <code>"

Notes:

"fn" can be one or more function names or regex; use "functions fn" to test the value of "fn"


 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>>



The aliase defined in the DebugShell are:


The alias vars lists all runtime variables with values:


 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> vars
*** constants
  __TRUE: "0"
  __FALSE: "1"
*** signal handling:
  BREAK_ALLOWED: "DebugShell"
  INSIDE_DIE: "1"
  INSIDE_DEBUG_SHELL: "0"
  INSIDE_CLEANUP_ROUTINE: "1"
  INSIDE_FINISH_ROUTINE: "1"
  INSIDE_USR1_HANDLER: "1"
  INSIDE_USR2_HANDLER: "1"
  INSIDE_BREAK_HANDLER: "1"
  INSIDE_HUP_HANDLER: "1"
  INSIDE_EXIT_HANDLER: "1"
  INSIDE_QUIT_HANDLER: "1"
*** Parameter:
  ALL_PARAMETER: "-D"
  NOT_USED_PARAMETER: ""
  FORCE: "1"
  QUIET: "1"
  VERBOSE: "1"
  VERBOSE_LEVEL: "0"
  USAGE_HELP: ""
  LIST_FUNCTIONS_AND_EXIT: "1"
  APPEND_LOG: "1"
  LOG_STDOUT: "0"
*** Hostname variables:
  CUR_HOST: "t540p"
  CUR_SHORT_HOST: "t540p"
  CUR_OS: "Linux"
*** Scriptname and directory:
  SCRIPTNAME: "scriptt_mini.sh"
  SCRIPTDIR: "."
  REAL_SCRIPTDIR: "/data/develop/scripts"
  REAL_SCRIPTNAME: "/data/develop/scripts/scriptt_mini.sh"
*** Current environment:
  CUR_SHELL: "/bin/ksh"
  EDITOR: "/usr/bin/vi"
  PAGER: "/usr/bin/less"
  WORKING_DIR: "/data/develop/scripts"
  LOGFILE: "/var/tmp/scriptt_mini.sh.log"
  LOGFILE_FOUND: "1"
  LOG_MESSAGE_CACHE: "
[28.02.2018 17:56 ] ### scriptt_mini.sh started at Wed Feb 28 17:56:46 CET 2018"
  ROTATE_LOG: "0"
  RUNNING_IN_TERMINAL_SESSION: "0"
  KSH_VERSION: "93"
  USE_ONLY_KSH88_FEATURES: "1"
  TYPESET_F_SUPPORTED: "yes"
  TRACE_FEATURE_SUPPORTED: "yes"
  AWK: "awk"
  ID: "id"
  __PPID: "18416"
*** Variables for the function AskUser:
  USER_INPUT: ""
  LAST_USER_INPUT: ""
  __NOECHO: "1"
  __USE_TTY: "1"
  __STTY_SETTINGS: ""
  __DEBUG_SHELL_IN_ASKUSER: "0"
*** User and group:
  CUR_USER_ID: "1000"
  CUR_USER_NAME: "xtrnaw7"
  CUR_GROUP_ID: "1000"
  CUR_GROUP_NAME: "xtrnaw7"
*** RCM variables:
  RCM_SERVICE: ""
  RCM_FUNCTION: ""
  RCM_HOSTID: ""
  RCM_HOSTID_FILE: "/var/db/var/hostid"
  RCM_DBQUERY: "/usr/db/RCM/Utility/dbquery"
  RCM_DBGET_FILE: "/usr/db/RCM/Utility/dbgetfile"
  RCM_USERID: ""
  RCM_PASSWORD: ""
*** Housekeeping:
  CLEANUP_FUNCTIONS: ""
  FILES_TO_REMOVE: "/tmp/scriptt_mini.sh.DebugShell.18785.1.tmp /tmp/scriptt_mini.sh.DebugShell.18785.2.tmp"
  DIRS_TO_REMOVE: ""
  PROCS_TO_KILL: ""
  KILL_PROC_TIMEOUT: "0"
  FINISH_FUNCTIONS: ""
*** Debugging
  __DEBUG_CODE: ""
  __FUNCTION_INIT: "eval __settraps"
  DEFAULT_DRYRUN_PREFIX: "echo "
  PREFIX: ""
  ENABLE_DEBUG: "0"
  __TEE_OUTPUT_FILE: "/var/tmp/scriptt_mini.sh.18785.tee.log"

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>>



To add variables to list for the alias vars add the variable names to list to the variable APPLICATION_VARIABLES. To add a string to print to that variable use

    #message_to_print

Blanks are not allowed in the strings for APPLICATION_VARIABLES but the alias will replace "_" with blanks in all lines that start with a hash "#":

Example:

# Code:
# ----------------------------------------------------------------------
# main code starts here
#

APPLICATION_VARIABLES="
#These_are_my_application_variables
MyVAR1
MyVAR2
"

...

MyVAR1="Value aaa"
MyVAR2="Value bbb ccc"

...

# then in DebugShell

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> vars
*** constants
  __TRUE: "0"
  __FALSE: "1" 

...

*** Housekeeping:
  DIRS_TO_REMOVE: ""
  FILES_TO_REMOVE: ""
  PROCS_TO_KILL: ""
*** These are my application variables
  MyVAR1: "Value aaa"
  MyVAR2: "Value bbb ccc"

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>>

The alias functions lists all defined functions known while executing the DebugShell:

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> functions
AskUser
check_rcm_values
cleanup
curtimestamp
DebugShell
__DebugShell
die
executeCommandAndLog
function_template
get_rcm_userid
isNumber
KillProcess
LogError
LogInfo
LogMsg
LogOnly
LogRuntimeInfo
LogWarning
print_runtime_variables
Read_APPL_PARAMS_entries
Retrieve_file_from_Jamaica
RotateLog
show_extended_usage_help
show_script_usage
signal_break_handler
signal_exit_handler
signal_hup_handler
signal_quit_handler
signal_usr1_handler
signal_usr2_handler

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>>


 

To view the source code of a function use "func <function_name>" (This works only if "typeset -f" is supported by your shell -- see above)


The parameter "fn" for the various aliase can be one or more function names or a regex or both; use the alias funcs to evaluate fn for testing e.g.

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> funcs LogInfo
 LogInfo

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> funcs Log*
 LogError LogInfo LogMsg LogOnly LogRuntimeInfo LogWarning

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> funcs Log* AskUser signal*
 LogError LogInfo LogMsg LogOnly LogRuntimeInfo LogWarning AskUser signal_break_handler signal_exit_handler signal_hup_handler signal_quit_handler signal_usr1_handler signal_usr2_handler

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> funcs *
 AskUser check_rcm_values cleanup curtimestamp DebugShell __DebugShell die __evaluate_fn executeCommandAndLog function_template get_rcm_userid isNumber KillProcess LogError LogInfo LogMsg LogOnly LogRuntimeInfo LogWarning print_runtime_variables Read_APPL_PARAMS_entries Retrieve_file_from_Jamaica RotateLog show_extended_usage_help show_script_usage signal_break_handler signal_exit_handler signal_hup_handler signal_quit_handler signal_usr1_handler signal_usr2_handler

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> funcs all
 AskUser check_rcm_values cleanup curtimestamp DebugShell __DebugShell die __evaluate_fn executeCommandAndLog function_template get_rcm_userid isNumber KillProcess LogError LogInfo LogMsg LogOnly LogRuntimeInfo LogWarning print_runtime_variables Read_APPL_PARAMS_entries Retrieve_file_from_Jamaica RotateLog show_extended_usage_help show_script_usage signal_break_handler signal_exit_handler signal_hup_handler signal_quit_handler signal_usr1_handler signal_usr2_handler

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> funcs signal_usr?_handler
 signal_usr1_handler signal_usr2_handler

  -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> func this_function_does_not_exist
The function this_function_does_not_exist is not defined


 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>>



To change the source code of a function in the running script use the aliase editfunc, savefunc, restorefunc, clearsavedfunc, viewsavedfunc, and savedfuncs (these aliase also only work if "typeset -f" is supported by your shell)


The alias editfunc can be used to change the source code of a function using the editor defined in the environment variable EDITOR, e.g.

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> func isNumber
function isNumber {
  typeset __FUNCTION="isNumber"
  ${__DEBUG_CODE}
  ${__FUNCTION_INIT}
   
  typeset THISRC=${__FALSE}

# old code:
#  typeset TESTVAR="$(echo "$1" | sed 's/[0-9]*//g' )"
#  [ "${TESTVAR}"x = ""x ] && return ${__TRUE} || return ${__FALSE}

  [[ $1 == +([0-9]) ]] && THISRC=${__TRUE} || THISRC=${__FALSE}

  return ${THISRC}
}


 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> isNumber 44
Executing now "eval isNumber 44" ...

---------
RC is 0

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> editfunc isNumber
Checking the new source code for "isNumber" using the shell /bin/ksh now ...
Enabling the new source code for "isNumber" now ...

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> func isNumber
function isNumber {
  typeset __FUNCTION="isNumber"
  ${__DEBUG_CODE}
  ${__FUNCTION_INIT}
   
  typeset THISRC=${__FALSE}

# old code:
#  typeset TESTVAR="$(echo "$1" | sed 's/[0-9]*//g' )"
#  [ "${TESTVAR}"x = ""x ] && return ${__TRUE} || return ${__FALSE}

  [[ $1 == +([0-9]) ]] && THISRC=${__TRUE} || THISRC=${__FALSE}
 
  echo "*** Inside isFunc, the parameter are: $*" >&2

  return ${THISRC}
}


 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> isNumber 44
Executing now "eval isNumber 44" ...
*** Inside isFunc, the parameter are: 44

---------
RC is 0

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>>


The alias editfunc can also be used to define new functions, e.g.

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> editfunc isNumber1
The function isNumber1 is not defined
Create a new function "isNumber1" (y/N)? y

Checking the new source code for "isNumber1" using the shell /bin/ksh now ...
Enabling the new source code for "isNumber1" now ...

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> func isNumber1
function isNumber1 {
  typeset __FUNCTION="isNumber1"
  ${__DEBUG_CODE}
  ${__FUNCTION_INIT}

  typeset THISRC=${__TRUE}

# add your code her
  echo "This is the new function isNumber1"

  return ${THISRC}
}


 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>>


editfunc
uses the function function_template (if defined) as template for new functions.

editFunc uses the editor saved in the environment variable EDITOR; the default editor to use if the variable EDITOR is not defined is $( which  vi ).


The aliase savefunc and restorefunc can be used to save and restore the current code for a function, e.g


 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> func LogInfo
function LogInfo {
  typeset __FUNCTION="LogInfo"
  ${__DEBUG_CODE}
  ${__FUNCTION_INIT}
   
  [ ${VERBOSE} = ${__TRUE} ] && LogMsg "INFO: $*" >&2
}




 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> savefunc LogInfo
Saving the current code for the function LogInfo ...

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>>

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> editfunc LogInfo
Checking the new source code for "LogInfo" using the shell /bin/ksh now ...
Enabling the new source code for "LogInfo" now ...

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> func LogInfo
function LogInfo {
  typeset __FUNCTION="LogInfo"
  ${__DEBUG_CODE}
  ${__FUNCTION_INIT}

  echo "*** Inside LogInfo ">&2
   
  [ ${VERBOSE} = ${__TRUE} ] && LogMsg "INFO: $*" >&2
}


 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> LogInfo "Test Message"
Executing now "eval LogInfo "Test Message"" ...
*** Inside LogInfo

---------
RC is 1

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>>

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> restorefunc LogInfo
Restoring the code for the function LogInfo ...

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> func LogInfo
function LogInfo {
  typeset __FUNCTION="LogInfo"
  ${__DEBUG_CODE}
  ${__FUNCTION_INIT}
   
  [ ${VERBOSE} = ${__TRUE} ] && LogMsg "INFO: $*" >&2
}


 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> LogInfo "Test Message"
Executing now "eval LogInfo "Test Message"" ...

---------
RC is 1

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>>


The alias savefunc always saves the current code for a function (that might be already changed using editfunc). You can only save each function ones, e.g:

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> savedfuncs
Saved functions are:  LogInfo 

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> savefunc LogInfo
The function LogInfo is already saved

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>>


The alias viewsavedfunc lists the contents of a saved function using the view program defined in the environment variable PAGER, e.g

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> PAGER=$( which cat )
Executing now "eval PAGER=$( which cat )" ...

---------
RC is 0

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> viewsavedfunc curtimestamp
Viewing the code for the saved function curtimestamp ...
function curtimestamp {
  typeset __FUNCTION="curtimestamp"    
  ${__DEBUG_CODE}
  ${__FUNCTION_INIT}
    
  date +%Y.%m.%d.%H_%M_%S_%s
}

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>>


The default value for the variable PAGER if it's not defined is $( which less ) or, if less is not found $( which more ).


The alias savedfuncs lists all saved functions and the alias clearsavedfunc deletes a saved function, e.g:

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> savedfuncs
Saved functions are:   LogInfo

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> clearsavedfunc LogInfo
Deleting the saved code for the function LogInfo ...

  -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> savedfuncs
There are no saved functions

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>>




You can use the aliase add_debug_code, view_debug, clear_debug, and set_debug to enable tracing (set -x) for one or more functions (see the section Tracing Functions above for the limitations of this feature)

To temporary add the statement "${__DEBUG_CODE}" to a function manually while running the script you can use the alias add_debug_code (only if the shell supports this feature) , e.g:


 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> func  MyFunction2
function MyFunction2 {
  typeset __FUNCTION="MyFunction2"
  ${__FUNCTION_INIT}
     
  typeset THISRC=${__TRUE}

  LogMsg "Inside of MyFunction2"
 
 
  return ${THISRC}
}



 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> add_debug_code MyFunction2
Adding debug code to the function MyFunction2 ...

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> func MyFunction2
function MyFunction2 {  typeset __FUNCTION=MyFunction2; ${__DEBUG_CODE};
  typeset __FUNCTION="MyFunction2"
  ${__FUNCTION_INIT}
     
  typeset THISRC=${__TRUE}

  LogMsg "Inside of MyFunction2"
 
 
  return ${THISRC}
}

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>>


Example for using set_debug:

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> view_debug
Debug code is currently enabled for these functions:


 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> functions
AskUser
check_rcm_values
cleanup
curtimestamp
DebugShell
__DebugShell
die
__evaluate_fn
executeCommandAndLog
function_template
get_rcm_userid
isNumber
KillProcess
LogError
LogInfo
LogMsg
LogOnly
LogRuntimeInfo
LogWarning
print_runtime_variables
Read_APPL_PARAMS_entries
Retrieve_file_from_Jamaica
RotateLog
show_extended_usage_help
show_script_usage
signal_break_handler
signal_exit_handler
signal_hup_handler
signal_quit_handler
signal_usr1_handler
signal_usr2_handler

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> set_debug MyFunction LogWarning
Enabling debug code for the function(s) "MyFunction LogWarning" now
Current settings for debug code are overwritten.
Enabling debug code for the function "MyFunction" ...
WARNING: The function "MyFunction" is not defined
Enabling debug code for the function "LogWarning" ...

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> view_debug
Debug code is currently enabled for these functions:
 MyFunction  LogWarning

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> LogWarning "Test Warning"
Executing now "eval LogWarning "Test Warning"" ...

*** Enabling trace for the function LogWarning ...
+ eval __settraps
+ LINENO=1
+ trap 'signal_hup_handler    ${LINENO}' 1
+ trap 'signal_break_handler  ${LINENO}' 2
+ trap 'signal_quit_handler   ${LINENO}' 3
+ trap 'signal_exit_handler   ${LINENO}' 15
+ trap 'signal_usr1_handler   ${LINENO}' USR1
+ trap 'signal_usr2_handler   ${LINENO}' USR2
+ LogMsg 'WARNING: Test Warning'
[03.03.2018 10:06 ] WARNING: Test Warning

---------
RC is 0

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> clear_debug
Clearing the debug code now ...

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> view_debug
Debug code is currently enabled for these functions:


 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> LogWarning "Test Warning"
Executing now "eval LogWarning "Test Warning"" ...
[03.03.2018 10:07 ] WARNING: Test Warning

---------
RC is 0

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>>
 

set_debug will automatically add the statement "${__DEBUG_CODE}" to a function if it's missing and the feature is supported by the shell, e.g.:

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> set_debug MyFunction2
Enabling debug code for the function(s) "MyFunction2" now
Adding debug code to the function MyFunction2 ...

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>>

Please note that set_debug overwrites the variable __DEBUG_CODE and therefor removes existing definitions.

To add additional functions to the existing list of functions with debug code use a leading plus "+", e.g.

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> set_debug  signal_usr1_handler signal_usr2_handler
Enabling debug code for the function(s) " signal_usr1_handler signal_usr2_handler" now
Current settings for debug code are overwritten.
Enabling debug code for the function "signal_usr1_handler" ...
Enabling debug code for the function "signal_usr2_handler" ...

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> view_debug
Debug code is currently enabled for these functions:
 signal_usr1_handler  signal_usr2_handler

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> set_debug +signal_quit_handler
Enabling debug code for the function(s) "+signal_quit_handler" now
Current settings for debug code ( signal_usr1_handler  signal_usr2_handler ) are preserved.
Enabling debug code for the function "signal_usr1_handler" ...
Enabling debug code for the function "signal_usr2_handler" ...
Enabling debug code for the function "signal_quit_handler" ...

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>> view_debug
Debug code is currently enabled for these functions:
 signal_usr1_handler  signal_usr2_handler  signal_quit_handler

 -------------------------------------------------------------------------------
scriptt_mini.sh - debug shell - enter a command to execute ("exit" to leave the shell)
Current environment: ksh version: 93 | change function code supported: yes | tracing feature using $0 supported: yes
>>


Note that you can call the function DebugShell at any time in your script



Other functions defined


scriptt_mini.sh defines some other useful functions :

Function
Used for
Comment
BackupFile
backup a file
Usage:

# BackupFile
#
# create a backup of a file if it exists
#
# usage: BackupFile sourcefile backupfile [backupfile_extension]
#
# returns:  ${__TRUE} - backup created or original file does not exist
#           ${__FALSE} - error creating the backup
#
#
isNumber
check if a value is an number
a value is a number if it contains only the digits from 0 to 9
curstimestamp write the current date and time to STDOUT the output of curtimestamp can be used in filenames
AskUser
ask the user for a value
If the parameter -y is used AskUser will always return ${__TRUE} without asking the user
If the parameter -n is used AskUser will always return ${__FALSE} without asking the user

The behaviour of AskUser can be changed using the variables __USE_TTY, __NOECHO, and __DEBUG_SHELL_IN_ASKUSER


KillProcess
kill one or more processes using kill and kill -9,
usage: KillProcess pid [...pid] 
The format for pid is "pid[:timeout_in_seconds]"

timeout_in_seconds is the time to wait after kill before a "kill -9" is issued if the process is still running;
use "pid:-1" to disable the "kill -9" for a process
Default timeout for all PIDs is KILL_PROC_TIMEOUT
create_lock_file
this function can be used to create a semaphor file to avoid multiple running instances of the script, e.g.

create_lock_file /var/tmp/your_semaphor_file.lock

# do whatever must be done while no other instance is runnig
# and remove the lock file when done

rm  /var/tmp/your_semaphor_file.lock


If the whole script should never run more then one time execute only

create_lock_file /var/tmp/your_semaphor_file.lock

at the beginning of your script. The semaphor file will the automatically deleted at script end in the house keeping code.

the usage of the function is

# create_lock_file
#
# function: create a lock file to avoid that multiple instances of this script are running at the same time
#
# usage: create_lock_file [lockfile] [wait_time] [wait_step_in_seconds]
#
# parameter:
#   lockfile - fully qualified name of the lock file
#     default: ${DEFAULT_LOCK_FILE}
#
#   wait_time - time in seconds (#S), minutes (#M), or hours (#H) to wait if the lockfile already exist
#     default : ${DEFAULT_LOCK_FILE_WAIT_TIME}
#
#   wait_step_in_seconds - wait pause in seconds
#     default: ${DEFAULT_STEP_COUNT}
#
# global varables used:
#
# WAIT_TIME_FOR_THE_LOCKFILE_IN_SECONDS
# PID_OF_PROCESS_HOLDING_THE_LOCKFILE
#
#                
# returns: 0 -  lock file created without waiting (probably after waiting for ${WAIT_TIME_FOR_THE_LOCKFILE_IN_SECONDS} seconds)
#          1 -  error creating the lock file
#          2 -  lock file already exists - could not create the lockfile, the variable
#               ${PID_OF_PROCESS_HOLDING_THE_LOCKFILE} contains the PID of the process holding the lockfile
#          3 -  usage error (invalid parameter, etc)
#          3 -  unknown error




get_fqn get the FQN of a file
gettime_in_seconds
retrieve the number of seconds since 1.1.1970
this function uses perl
read_file_section
read the lines of a file between start_regex and end_regex
usage: read_file_section [filename] [start_regex] [end_regex]
is_variable_true check if a variable is true (-> checks for various values - see source code)

convert_variable_to_boolean convert a boolean variable to ${__TRUE} or ${__FALSE}



function_template this is only a template for new functions This function is used as template by the DebugShell alias editfunc for new functions if defined.



check_rcm_values
get_rcm_userid
Read_APPL_PARAMS_entries
Retrieve_file_from_Jamaica
special functions for an RCM environment -- just ignore or delete these functions if not used




User defined functions


To use all features of the template you should define new functions like this

# ----------------------------------------------------------------------
# function_template
#
# function:
#
# usage:
#
# returns: ${__TRUE} -
#          ${__FALSE} -
#
function function_template {
  typeset __FUNCTION="function_template"
  ${__FUNCTION_INIT}
  ${__DEBUG_CODE}

  typeset THISRC=${__TRUE}

# add your code her

  return ${THISRC}
}

The function function_template is used by the DebugShell alias editfunc if available - so you should not delete it.



Links



http://bnsmb.de/solaris/scriptt.html
scriptt.sh , a more complex shell script template
http://www.shelldorado.com/
Heiner's Shell Dorado
http://apenwarr.ca/log/?m=201102#28
Insufficiently known POSIX shell features
http://blog.fpmurphy.com/2008/10/ksh93-date-manipulation.html
ksh93 builtin time formatting with printf examples
http://www.unix.com/unix-dummies-questions-answers/13018-exit-status-command-pipe-line.html#post47559
source for the function executeCommandAndLog
https://stackoverflow.com/questions/24412721/elegant-solution-to-implement-timeout-for-bash-commands-and-functions#
code used for the function runcmd_with_timeout



Download

Download scriptt_mini.sh



back top top