----------------------------------------------------------------------------------------------------- scriptt.sh v1.0.0 (Scripttemplate: 2.3.0.0 10.11.2017 /bs) Documentation ----------------------------------------------------------------------------------------------------- scriptt.sh - ??? script description ??? Author: Bernd Schemmer (Bernd.Schemmer@gmx.de) Version: see variable ${__SCRIPT_VERSION} below (see variable ${__SCRIPT_TEMPLATE_VERSION} for the template version used) Supported OS: Solaris, Linux, AIX and other Unix flavours Description ----------- ??? Note: The current version of the script template can be found here: http://bnsmb.de/solaris/scriptt.html Configuration file ------------------ This script supports a configuration file called .conf. The configuration file is searched at script start in the working directory, the home directory of the user executing this script and in /etc (in this order). The configuration file is read before the parameter are processed. To override the default config file search set the variable CONFIG_FILE to the name of the config file to use. e.g. CONFIG_FILE=/var/myconfigfile ./scriptt.sh To disable the use of a config file use CONFIG_FILE=none ./scriptt.sh See the variable __CONFIG_PARAMETER below for the possible entries in the config file. To create a new config file use the parameter "-C" Predefined parameter -------------------- see the subroutines ShowShortUsage and ShowUsage Troubleshooting support ----------------------- Per default CTRL-C calls the DebugShell The DebugShell is in principle a loop to read input from the user and then execute that input via eval. DebugShell knows some internal aliase - everything else is interpreted as an OS or script command to execute. The online help for the DebugShell is: *** Debug Shell called via CTRL-C *** ------------------------------------------------------------------------------- scriptt.sh - debug shell (called via CTRL-C) - enter a command to execute ("exit" to leave the shell) defined aliase: functions = list all defined functions, vars [help|var_list] = print global variables, quit = exit the script, abort = abort the script with kill -9, use help for a short usage help cont = continue script execution >> help Enter either an defined alias or an OS command to execute Defined aliase are: functions - print all defined functions func f1 [...f#] - view the source code for the functions f1 to f# (supported by this shell: yes) add_debug_code f1 [...f#] - add debug code to functions f1 to f#; use all for f1 to add debug code to all functions (supported by this shell: yes) view_debug - view the current debug code set_debug f1 [...f#] - enable tracing for the functions f1 to f# Note: The existing trace definitions will be overwritten! clear_debug - disable tracing for all functions vars help - print defined variable lists vars var_list - print the variable from the variable list 'var_list' vars all - print all variables verbose - toggle the verbose switch (current value is: 1, __VERBOSE_LEVEL is 0) break - toggle the break switch (current value is: 0) exit - exit the shell quit - exit the script abort - exit the script with 'kill -9' cont - continue the script execution Everthing else is interpreted as an OS command Note: The alias "cont" is only available if DebugShell is called in the CTRL-C signal handller. ------------------------------------------------------------------------------- scriptt.sh - debug shell (called via CTRL-C) - enter a command to execute ("exit" to leave the shell) defined aliase: functions = list all defined functions, vars [help|var_list] = print global variables, quit = exit the script, abort = abort the script with kill -9, use help for short usage help cont = continue script execution >> vars help Known variable lists are: all - print all variables used application - print application variables used_env - print environment variables used log - print variables for the logfile handling defaults - print variables with DEFAULT_* values config - print variables for the config file processing house_keeping - print variables for the housekeeping processing signalhandler - print variables for the signal handler dump - print variables for the dump processing script - print variables with the script name, directory, etc debug - print variables for the debug functions parameter - print variables for the parameter requirements - print variables for the script requirements runtime - print various runtime variables os_env - print variables for the OS environment internal - print all internal variables execept these variables __LONG_USAGE_HELP __SHORT_USAGE_HELP __OTHER_USAGE_EXAMPLES __CONFIG_PARAMETER ------------------------------------------------------------------------------- scriptt.sh - debug shell (called via CTRL-C) - enter a command to execute ("exit" to leave the shell) defined aliase: functions = list all defined functions, vars [help|var_list] = print global variables, quit = exit the script, abort = abort the script with kill -9, use help for short usage help cont = continue script execution >> Use __CREATE_DUMP= to create a dump of the environment variables on program exit. e.g __CREATE_DUMP=1 ./scriptt.sh will create a dump of the environment variables in the files /tmp/scriptt.sh.envvars.$$ /tmp/scriptt.sh.exported_envvars.$$ before the script ends __CREATE_DUMP=/var/tmp/debug ./scriptt.sh will create a dump of the environment variables in the files /var/tmp/debug/scriptt.sh.envvars.$$ /var/tmp/debug/scriptt.sh.exported_envvars.$$ before the script ends (the target directory must already exist). Note that the dump files will always be created in case of a syntax error. To set the directory for these files use either export __DUMPDIR=/var/tmp/debug ./scriptt.sh or define __DUMPDIR in the script. To suppress creating the dump file in case of a syntax error add the statement __DUMP_ALREADY_CREATED=0 to your script Use CreateDump [filename_add] to manually create the dump files from within the script. e.g. CreateDump /var/debug will create the files /var/debug/scriptt.sh.envvars.$$ /var/debug/scriptt.sh.exported_envvars.$$ CreateDump /var/debug pass2. will create the files /var/debug/scriptt.sh.envvars.pass2.$$ /var/debug/scriptt.sh.exported_envvars.pass2.$$ Note: The default action for the signal handler USR1 is "Create an environment dump in /var/tmp" The filenames for the dumps are /var/tmp/.envvars.dump_no__ /var/tmp/.exported_envvars.dump_no__ where is a sequential number, is the PID of the process with the script, and is the name of the script without the path. In addition there are some debug parameters that can be used to search and fix errors in the script -- see the output of script.sh -D help for the list of known debug switches. ----------------------------------------------------------------------------- Note: Use ./scriptt.sh -D SyntaxHelp 2>./scriptt.sh.syntaxhelp to get some syntax examples for the functions defined in the template. ----------------------------------------------------------------------------- User defined signal handler --------------------------- You can define various SIGNAL handlers to process signals received by the script. All SIGNAL handlers can use these variables: __TRAP_SIGNAL -- the catched trap signal (this variable is NOT reset when the signal handler ended) INTERRUPTED_FUNCTION -- the function interrupted by the signal To define one signal handler for all signals do: __GENERAL_SIGNAL_FUNCTION= To define unique signal handler for the various signals do: __SIGNAL_SIGUSR1_FUNCTION= __SIGNAL_SIGUSR2_FUNCTION= __SIGNAL_SIGHUP_FUNCTION= __SIGNAL_SIGINT_FUNCTION= __SIGNAL_SIGQUIT_FUNCTION= __SIGNAL_SIGTERM_FUNCTION= If both type of signal handler are defined the script first executes the general signal handler. If this handler returns 0 the handler for the catched signal will also be executed (else not). If the unique handler for the signal ends with 0 the default signal handler for this signal will also be executed (else not) Credits ------- Hints regarding the code to create the lockfile wpollock (http://wikis.sun.com/display/~wpollock) Source for the function PrintWithTimeStamp (in version 2.x and newer): http://unix.stackexchange.com/questions/26728/prepending-a-timestamp-to-each-line-of-output-from-a-command Andreas Obermaier for a security issue in the lockfile routine (see history section 1.22.45 07.06.2012) The code used in executeCommandAndLog is from http://www.unix.com/unix-dummies-questions-answers/13018-exit-status-command-pipe-line.html#post47559 Thanks to Arno Teunisse for some usage examples for scriptt.sh History: -------- ??.??.2017 v1.0.0 /bs initial release script template History ----------------------- 1.22.0 08.06.2006 /bs (BigAdmin Version 1) public release; starting history for the script template 1.22.1 12.06.2006 /bs added true/false to CheckYNParameter and ConvertToYesNo 1.22.2. 21.06.2006 /bs added the parameter -V added the use of environment variables added the variable __NO_TIME_STAMPS added the variable __NO_HEADERS corrected a bug in the function executeCommandAndLogSTDERR added missing return commands 1.22.3 24.06.2006 /bs added the function StartStop_LogAll_to_logfile added the variable __USE_TTY (used in AskUser) corrected a typo (dev/nul instead of /dev/null) 1.22.4 06.07.2006 /bs corrected a bug in the parameter error handling routine 1.22.5 27.07.2006 /bs corrected some minor bugs 1.22.6 09.08.2006 /bs corrected some minor bugs 1.22.7 17.08.2006 /bs add the CheckParameterCount function added the parameter -T added long parameter support (e.g --help) 1.22.8 07.09.2006 /bs added code to save the env variable LANG and set it temporary to C 1.22.9 20.09.2006 /bs corrected code to save the env variable LANG and set it temporary to C 1.22.10 21.09.2006 /bs cleanup comments the number of temporary files created automatically is now variable (see the variable __NO_OF_TEMPFILES) added code to install the trap handler in all functions 1.22.11 19.10.2006 /bs corrected a minor bug in AskUser (/c was not interpreted by echo) corrected a bug in the handling of the parameter -S (-S was ignored) 1.22.12 31.10.2006 /bs added the variable __REQUIRED_ZONE 1.22.13 13.11.2006 /bs the template now uses TMP or TEMP if set for the temporary files 1.22.14 14.11.2006 /bs corrected a bug in the function AskUser (the default was y not n) 1.22.15 21.11.2006 /bs added initial support for other Operating Systems 1.22.16 05.07.2007 /bs enhanced initial support for other Operating Systems Support for other OS is still not fully tested! 1.22.17 06.07.2007 /bs added the global variable __TRAP_SIGNAL 1.22.18 01.08.2007 /bs __OS_VERSION and __OS_RELEASE were not set - corrected 1.22.19 04.08.2007 /bs wrong function used to print "__TRAP_SIGNAL is \"${__TRAP_SIGNAL}\"" - fixed 1.22.20 12.09.2007 /bs the script now checks the ksh version if running on Solaris made some changes for compatibility with ksh93 1.22.21 18.09.2007 /bs (BigAdmin Version 2) added the variable __FINISHROUTINES changed __REQUIRED_ZONE to __REQUIRED_ZONES added the variable __KSH_VERSION reworked the trap handling 1.22.22 23.09.2007 /bs added the signal handling for SIGUSR1 and SIGUSR2 (variables __SIGUSR1_FUNC and __SIGUSR2_FUNC) added user defined function for the signals HUP, BREAK, TERM, QUIT, EXIT, USR1 and USR2 added the variables __WARNING_PREFIX, __ERROR_PREFIX, __INFO_PREFIX, and __RUNTIME_INFO_PREFIX the parameter -T or --tee can now be on any position in the parameters the default output file if called with -T or --tee is now /var/tmp/${0##*/}.$$.tee.log 1.22.23 25.09.2007 /bs added the environment variables __INFO_PREFIX, __WARNING_PREFIX, __ERROR_PREFIX, and __RUNTIME_INFO_PREFIX added the environment variable __DEBUG_HISTFILE reworked the function to print the usage help : use "-h -v" to view the extented usage help and use "-h -v -v" to view the environment variables used also 1.22.24 05.10.2007 /bs another minor fix for ksh93 compatibility 1.22.25 08.10.2007 /bs only spelling errors corrected 1.22.26 19.11.2007 /bs only spelling errors corrected 1.22.27 29.12.2007 /bs improved the code to create the lockfile (thanks to wpollock for the info; see credits above) improved the code to create the temporary files (thanks to wpollock for the info; see credits above) added the function rand (thanks to wpollock for the info; see credits above) the script now uses the directory name saved in the variable $TMPDIR for temporary files if it's defined now the umask used for creating temporary files can be changed (via variable __TEMPFILE_UMASK) 1.22.28 12.01.2008 /bs corrected a syntax error in the show usage routine added the function PrintWithTimestamp (see credits above) 1.22.29 31.01.2008 /bs there was a bug in the new code to remove the lockfile which prevented the script from removing the lockfile at program end if the lockfile already exist the script printed not the correct error message 1.22.30 28.02.2008 /bs Info update: executeCommandAndLog does NOT return the RC of the executed command if a logfile is defined added inital support for CYGWIN (tested with CYGWIN_NT-5.1 v..1.5.20(0.156/4/2) Most of the internal functions are NOT tested yet in CYGWIN GetCurrentUID now supports UIDs greater than 254; the function now prints the UID to STDOUT Corrected bug in GetUserName (only a workaround, not the solution) now using printf in the AskUserRoutine 1.22.30 28.02.2008 /bs The lockfile is now also deleted if the script crashes because of a syntax error or something like this 1.22.31 18.03.2008 /bs added the version number to the start and end messages an existing config file is now removed (and not read) if the script is called with -C to create a config file 1.22.32 04.04.2008 /bs minor changes for zone support 1.22.33 12.02.2009 /bs disabled the usage of prtdiag due to the fact that prtdiag on newer Sun machines needs a long time to run (-> __MACHINE_SUBTYPE is now always empty for Solaris machines) added the variable __CONFIG_FILE_FOUND; this variable contains the name of the config file read if a config file was found added the variable __CONFIG_FILE_VERSION 1.22.34 28.02.2009 /bs added code to check for the max. line no for the debug handler (an array in ksh88 can only handle up to 4096 entries) added the variable __PIDFILE 1.22.35 06.04.2009 /bs added the variables __NO_CLEANUP __NO_EXIT_ROUTINES __NO_TEMPFILES_DELETE __NO_TEMPMOUNTS_UMOUNT __NO_TEMPDIR_DELETE __NO_FINISH_ROUTINES __CLEANUP_ON_ERROR CONFIG_FILE 1.22.36 11.04.2009 /bs corrected a cosmetic error in the messages (wrong: ${TEMPFILE#} correct: ${__TEMPFILE#}) 1.22.37 08.07.2011 /bs corrected a minor error with the QUIET parameter added code to dump the environment (env var __CREATE_DUMP, function CreateDump ) implemented work around for missing function whence in bash added the function LogIfNotVerbose 1.22.38 22.07.2011 /bs added code to make the trap handling also work in bash added a sample user defined trap handler (function USER_SIGNAL_HANDLER) added the function SetHousekeeping to enabe or disable house keeping scriptt.sh did not write all messages to the logfile if a relative filename was used - fixed added more help text for "-v -v -v -h" now user defined signal handler can have arguments the RBAC feature (__USE_RBAC) did not work as expected - fixed added new scriptt testsuite for testing the script template on other OS and/or shells added the function SaveEnvironmentVariables 1.22.39 24.07.2011 /bs __INIT_FUNCTION now enabled for cygwin also __SHELL did not work in all Unixes - fixed __OS_FULLNAME is now also set in Solaris and Linux 1.22.40 25.07.2011 /bs added some code for ksh93 (functions: substr) Note: set __USE_ONLY_KSH88_FEATURES to ${__TRUE} to suppress using the ksh93 features The default action for the signal handler USR1 is now "Create an env dump in /var/tmp" The filenames for the dumps are /var/tmp/.envvars.dump_no__ /var/tmp/.exported_envvars.dump_no__ where is a sequential number, is the PID of the process with the script, and is the name of the script without the path. 1.22.41 26.09.2011 /bs added the parameter -X disabled some ksh93 code because "ksh -x -n" using ksh88 does not like it 1.22.42 05.10.2011 /bs added the function PrintDotToSTDOUT 1.22.43 15.10.2011 /bs added support for disabling the config file feature with CONFIG_FILE=none ./scriptt.sh corrected a minor bug in SaveEnvironmentVariables corrected a bug in the function SaveEnvironmentVariables corrected a bug in getting the value for the variable ${__ABSOLUTE_SCRIPTDIR} 1.22.44 22.04.2012 /bs The script now uses nawk only if available (if not awk is used) add a line with the current date and time to variable dumps, e.g. ### /var/tmp/scriptt.sh.exported_envvars.dump_no_0_20074 - exported environment variable dump created on Sun Apr 22 11:35:38 CEST 2012 ### /var/tmp/scriptt.sh.envvars.dump_no_0_20074 - environment variable dump created on Sun Apr 22 11:35:38 CEST 2012 added experimental interactive mode to the signal handler for USR2 replaced /usr/bin/echo with printf added the variable LOGMSG_FUNCTION 1.22.45 07.06.2012 /bs added code to check if the symbolic link for the lockfile already exists before creating the lock file 1.22.46 27.04.2013 /bs executeCommandAndLog rewritten using coprocesses (see also credits) Info update: executeCommandAndLog does now return the RC of the executed command even if a logfile is defined ------------------------------------------------------------------- 2.0.0.0 17.05.2013 /bs added the variable __GENERAL_SIGNAL_FUNCTION: This variable contains the name of a function that is called for all SIGNALs before the special SIGNAL handler is called removed the Debug Handler for single step execution (due to the length of the template it is not useful anymore; use the version 1.x of scriptt.sh if you still need the Debug Handler) function executeCommandAndLogSTDERR rewritten removed the function CheckParameterCount use lsb_release in Linux to retrieve OS infos if available minor fixes for code and comments replaced PrintWithTimeStamp with code that does not use awk isNumber replaced with code that does not use sed 2.0.0.1 06.08.2013 /bs added the variable __MACHINE_SUB_CLASS. Possible values for sun4v machines: either "GuestLDom" or "PrimaryLDom" 2.0.0.2 01.09.2013 /bs added the variables __SYSCMDS and __SYSCMDS_FILE 2.0.0.3 16.12.2013 /bs now the Log-* functions return ${__TRUE} if a message is printed and ${__FALSE} if not 2.0.0.4 01.01.2014 /bs the alias __settrap is renamed to settraps (with leading s) two new aliase are defined: __ignoretraps and __unsettraps whence function for non-ksh compatible shells rewritten without using ksh the switch -D is now used to toggle debug switches known debug switches: help -- print the usage help for -D msg -- log debug messages to /tmp/..debug trace -- activate tracing to the file /tmp/..trace AskUser now accepts also "yes" and "no" function IsFunctionDefined rewritten now __LOGON_USERID and __USERID are equal to $LOGNAME until I find a working solution (the code in the previous version did not work if STDIN is not a tty) 2.0.0.5 08.01.2014 /bs added the function executeFunctionIfDefined 2.0.0.6 27.01.2014 /bs added the function PrintLine added the functions GetSeconds, GetMinutes, ConvertMinutesToHours, and GetTimeStamp added the debug options fn_to_stderr, fn_to_tty, and fn_to_handle9 max. return value for a function is 255 and therefor the functions for the stack and the functions pos and lastpos now abort the script if a value greater than 255 should be returned added the variables __SHEBANG, __SCRIPT_SHELL, and __SCRIPT_SHELL_OPTIONS added the function DebugShell AskUser now has a hidden shell; use "shell" to call the DebugShell set __DEBUG_SHELL_IN_ASKUSER to ${__FALSE} to disable the DebugShell in AskUser added the function ConvertDateToEpoc 2.0.0.7 27.04.2014 /bs AskUser now saves the last input in the variable LAST_USER_INPUT, to enter this value again use "#last" Version parameter (-V) usage enhanced: use "-v -v -V" to print also the version history; use "-v -v -v -V" to also print the template version history. 2.1.0.0 02.11.2014 /bs Added the parameter "-D SyntaxHelp" to print syntax usage examples for the template Added the parameter "-D debugcode='x' " Added the parameter "-D tracefunc=f1" Added the parameter "-D setvar:name=value" Added more usage information for the template 2.1.0.1 04.11.2014 /bs Added the parameter variable__DEBUG_PREFIX Added the function LogDebugMsg Added the parameter "-D listfunc" Added the parameter "-D fn_to_device=filename" corrected a minor bug in the parameter handling for the parameter "-D" 2.1.0.2 06.11.2014 /bs Added the parameter "-D create_dump=d" the function rand now uses nawk in Solaris and awk in all other OS 2.1.0.2 08.11.2014 /bs corrected a bug in code for the parameter "-D fn_to_device=filename" added ${__FUNCTION_EXIT} to some of the functions 2.1.0.3 12.12.2014 /bs added the variable ${__BACKUP_FILE} to BackupFileIfNecessary 2.1.0.4 25.12.2014 /bs __SCRIPTDIR was wrong if the script was called with the name only 2.1.0.5 08.05.2015 /bs LogRuntimeInfo did not work in the default ksh from Solaris 11 --fixed 2.1.0.6 08.07.2015 /bs Added the parameter "-D debug" 2.1.0.7 25.07.2015 /bs added the parameter "-D dryrun". To use dryrun in your code add the prefix "${PREFIX}" to every external command executed by your script added the parameter "-D list_rc" to list all return codes used in the script (only works if you only use "die" to end the script) 2.1.0.8 09.09.2015 /bs added the variable __SETOPTS and the alias __TRACE_ACTIVE 2.1.0.9 26.10.2015 /bs added the keyword printargs to the parameter -D BackupFileIfNecessary now supports rotating backups, e.g. file.0, file.1, file.3, ... To use that feature the new format of the parameter for the function is: BackupFileIfNeccessary [file{,no_of_backups}] [...] In the default configuration the script now creates a new log file for each execution of the script and retains up to 10 backups of the log file. To overwrite the number of backups use the following syntax for the parameter -l: -l logfile,[no_of_backups_of_the_logfile] The default number of backups for the log file is configured in the variable MAX_NO_OF_LOGFILES 2.1.0.10 16.11.2015 /bs replaced code incompatible with some ksh versions 2.1.0.11 26.11.2015 /bs moved initialisation of __SCRIPTNAME, __SCRIPTDIR, and __REAL_SCRIPTDIR to the beginnning of the script automatic umount of mount points via __LIST_OF_TMP_MOUNTS did not work anymore - fixed some cosmetic changes 2.2.0.0 09.01.2016 /bs the function GetKeystroke did not process the parameter - fixed GetKeystroke did not check for CTRL-C - fixed the function GetKeystroke now supports the parameter [lower|upper] to convert the user input to lowercase or uppercase; the real user input is still available in the global variable RAW_USER_INPUT the script now prints the actions that would have been done in the cleanup routine if __NO_CLEANUP is set added the parameter "-D nocleanup" (shortcut for "-D setvar:__NO_CLEANUP=0") added the parameter "-D cleanup[=type]" to enable/disable the house keeping die() will now again end the script even if -f was used includeScript now checks the syntax of an include script added the function tryIncludeScript added the parameter "-D showdefaults" added the parameter "-D tracemain" corrected some errors in the messages written by the script reworked the comments in the script added the variable __START_DIR_REAL 2.2.0.1 17.01.2016 /bs the content of the environment variable __DEBUG_CODE was not used -- fixed adding -f to the rm and mv commands in BackupFileIfNecessary __BACKUP_FILE was not always set to the correct value in BackupFileIfNecessary - fixed now BackupFileIfNecessary returns ${__FALSE} if one or more backups failed 2.2.0.2 24.10.2016 /bs SDTERR in DebugShell was not redirected to /dev/tty -- fixed DebugShell returns now immediately if not running in an interactive session 2.3.0.0 10.11.2017 /bs scriptt.sh added the variable __RUNNING_IN_TERMINAL_SESSION added the function print_runtime_variables enhanced the function DebugShell default user defined trap handler for CTRL-C is now DebugShell edit the line __SIGNAL_SIGINT_FUNCTION="DebugShell" to change this behaviour or use ./scriptt.sh -D setvar:__SIGNAL_SIGINT_FUNCTION="" if the script is called with redirected STDIN and without the parameter -q all output for STDOUT and STDERR is now redirected to the file /var/tmp/${0##*/}.STDOUT_STDERRR.$$ removed the variables SCRIPT_USER and SCRIPT_USER_MSG added the variables __PROCS_TO_KILL and __PROCS_KILL_TIMEOUT to define processes that should be stopped at script end the debug switch "-D tracefunc" can now be used more then one time the debug switches "-D tracefunc" and "-D debug" can be used at the same time the debug switch "-D tracefunc" now supports the variable ${.sh.func} if running in ksh93 added the debug switch "-D DebugShell" to call the DebugShell while processing the parameter fixed a typo: renamed __ingoretraps to __ignoretraps the function f() to check the ksh version is now deleted after it is used "typeset -f" replaced with "typeset +f" where applicable the default value for the debug switch "-D cleanup" is now "all" added the variable __TYPESET_F_SUPPORTED; this variable is set to "yes" if "typeset -f function" can be used to print the statements of a function in the used shell the debug switch "-D tracefunc" and the aliase for tracing in DebugShell now add the statements typeset __FUNCTION= ; ${__DEBUG_CODE}; to a function if neccessary, and "typeset -f" is supported by the shell used the cleanup function now supports parameter for the exit routines the cleanup function now supports parameter for the finish routines added the variable __INSIDE_EXIT_ROUTINE added the variable __INSIDE_FINISH_ROUTINE ##### constants __TRUE - true (0) __FALSE - false (1) ---------------- Version variables __SCRIPT_VERSION - the version of your script __SCRIPT_TEMPLATE_VERSION - version of the script template __SCRIPTNAME - name of the script without the path __SCRIPTDIR - path of the script (as entered by the user!) __REAL_SCRIPTDIR - path of the script (real path, maybe a link) __SHORT_DESC - short description (for help texts, etc) Change to your need __LONG_USAGE_HELP - Additional help if the script is called with the parameter "-v -h" Note: To use variables in the help text use the variable name without an escape character, eg. ${OS_VERSION} __SHORT_USAGE_HELP - Additional help if the script is called with the parameter "-h" Note: To use variables in the help text use the variable name without an escape character, eg. ${OS_VERSION} ---------------- Predefined return codes: ------------------------ 0 - ok, no error 1 - show usage and exit 2 - invalid parameter found 3 - 209 These returncodes can be used by the application code 210 - 254 reserved for the runtime system 228 - There is an error in an include script 229 - Script aborted by the user 230 - Script does not exist or is not readable 231 - Can not write to the file \"${CUR_VAR}\" 232 - Function SyntaxHelp NOT defined. 233 - Can not write to file handle 9 234 - The return value is greater than 255 in function x 235 - Invalid debug switch found 236 - syntax error 237 - Can not write to the debug log file 238 - unsupported Operating system 239 - script runs in a not supported zone 240 - internal error 241 - a command ended with an error (set -e is necessary to activate this trap) 242 - the current user is not allowed to execute this script 243 - invalid machine architecture 244 - invalid processor type 245 - invalid machine platform 246 - error writing the config file 247 - include script not found 248 - unsupported OS version 249 - Script not executed by root 250 - Script is already running 251 - QUIT signal received 252 - User break 253 - TERM signal received 254 - unknown external signal received ---------------- Used environment variables __DEBUG_CODE __RT_VERBOSE_LEVEL __QUIET_MODE __VERBOSE_MODE __VERBOSE_LEVEL __OVERWRITE_MODE __USER_BREAK_ALLOWED __NO_TIME_STAMPS __NO_HEADERS __USE_COLORS __USE_RBAC __RBAC_BINARY __TEE_OUTPUT_FILE __INFO_PREFIX __DEBUG_PREFIX __WARNING_PREFIX __ERROR_PREFIX __RUNTIME_INFO_PREFIX __NO_CLEANUP __NO_KILL_PROCS __PROCS_KILL_TIMEOUT __NO_EXIT_ROUTINES __NO_TEMPFILES_DELETE __NO_TEMPMOUNTS_UMOUNT __NO_TEMPDIR_DELETE __NO_FINISH_ROUTINES __CLEANUP_ON_ERROR __CREATE_DUMP __DUMP_ALREADY_CREATED __DUMPDIR __USE_ONLY_KSH88_FEATURES CONFIG_FILE ---------------- ##### general hints Do not use variable names beginning with __ (these are reserved for internal use) __KSH_VERSION - ksh version (either 88 or 93) If the script is not executed by ksh the shell is compatible to ksh version ${__KSH_VERSION} check if "typeset -f" is supported __OS - Operating system (e.g. SunOS) __SETOPTS - active set options at script start __TRACE_ACTIVE - alias, write ${__TRUE} to stdout if "set -x" is active else ${__FALSE} __SHEBANG - shebang of the script __SCRIPT_SHELL - shell in the shebang of the script __SCRIPT_SHELL_OPTIONS - shell options in the shebang of the script __SHELL - name of the current shell executing this script -------------------------------------------------------------------------- internal variables __LOG_DEBUG_MESSAGES - log debug messages if set to true This can be activated with the parameter -D msg __DEBUG_SHELL_IN_ASKUSER - enable or disable the debug shell in AskUser __ACTIVATE_TRACE - log trace messages (set -x) if set to true This can be activated with the parameter -D trace __TRAP_SIGNAL - current trap caught by the trap handler This is a global variable that can be used in the exit routines __USE_RBAC - set this variable to ${__TRUE} to execute this script with RBAC default is ${__FALSE} Note: You can also set this environment variable before starting the script __RBAC_BINARY - pfexec binary default is /usr/bin/pfexec Note: You can also set this environment variable before starting the script __TEE_OUTPUT_FILE - name of the output file if called with the parameter -T default: /var/tmp/$( basename $0 ).$$.tee.log Note: You can also set this environment variable before starting the script ##### defined variables that may be changed __DEBUG_CODE - code executed at start of every sub routine Note: Use always "__DEBUG_CODE="eval ..." if you want to use variables or aliases Default debug code : none sample debug code: __DEBUG_CODE=" eval echo Entering the subroutine \${__FUNCTION} ... " Note: Use an include script for more complicated debug code, e.g. __DEBUG_CODE=" eval . /var/tmp/mydebugcode" __FUNCTIONS_TO_TRACE - functions for which trace (set -x) is enable __FUNCTION_INIT - code executed at start of every sub routine (see the hints for __DEBUG_CODE) Default init code : install the trap handlers __FUNCTION_EXIT - code executed at end of every sub routine (see the hints for __DEBUG_CODE) Default exit code : "" variables for debugging __NO_CLEANUP - do not call the cleanup routine at all at script end if ${__TRUE} __NO_EXIT_ROUTINES - do not execute the exit routines if ${__TRUE} __NO_KILL_PROCS - do not kill the processes at script end if ${__TRUE} __NO_TEMPFILES_DELETE - do not remove temporary files at script end if ${__TRUE} __NO_TEMPMOUNTS_UMOUNT - do not umount temporary mount points at script end if ${__TRUE} __NO_TEMPDIR_DELETE - do not remove temporary directories at script end if ${__TRUE} __NO_FINISH_ROUTINES - do not execute the finish routeins at script end if ${__TRUE} __CLEANUP_ON_ERROR - call cleanup if the script was aborted by a syntax error __CONFIG_PARAMETER The variable __CONFIG_PARAMETER contains the configuration variables The defaults for these variables are defined here. You can use a config file to overwrite the defaults. Use the parameter -C to create a default configuration file Note: The config file is read and interpreted via ". configfile" therefore you can also add some code here BACKUP_EXTENSION - extension for backup files MAX_NO_OF_LOGFILES - number of backups for the log file Default: create up to 10 backups of the log file __DUMP_ALREADY_CREATED - do not automatically create another dump if this variable is ${__TRUE} __CREATE_DUMP - create an environment dump if the scripts exits with error (replace with either 0 or the directory for the dumps) to always create a dump at script end DEFAULT_DUMPDIR - default directory for environment dumps default for the parameter -D dryrun DEFAULT_PREFIX="" __MUST_BE_ROOT - run script only by root (def.: false) set to ${__TRUE} for scripts that must be executed by root only __REQUIRED_USERID - required userid to run this script (def.: none) use blanks to separate multiple userids e.g. "oracle dba sysdba" "" = no special userid required (see also the variable __MUST_BE_ROOT) __REQUIRED_ZONES - required zones (either global, non-global or local or the names of the valid zones) This is a Solaris only feature! (def.: none) "" = no special zone required __ONLY_ONCE - run script only once at a time (def.: false) set to ${__TRUE} for scripts that can not run more than one instance at the same time __ REQUIRED_OS - required OS (uname -s) for the script (def.: none) use blanks to separate the OS names if the script runs under multiple OS e.g. "SunOS" __REQUIRED_OS_VERSION - required OS version for the script (def.: none) minimum OS version necessary, e.g. 5.10 "" = no special version necessary __REQUIRED_MACHINE_PLATFORM - required machine platform for the script (def.: none) required machine platform (uname -i) , e.g "i86pc"; use blanks to separate the multiple machine types, e.g "Sun Fire 3800 i86pc" "" = no special machine type necessary __REQUIRED_MACHINE_CLASS - required machine class for the script (def.: none) required machine class (uname -m) , e.g "i86pc" ; use blanks to separate the multiple machine classes, e.g "sun4u i86pc" "" = no special machine class necessary __REQUIRED_MACHINE_ARC - required machine architecture for the script (def.: none) required machine architecture (uname -p) , e.g "i386" ; use blanks to separate the machine architectures if more than one entry, e.g "sparc i386" "" = no special machine architecture necessary __VERBOSE_LEVEL - count of -v parameter (def.: 0) Note: You can also set this environment variable before starting the script __RT_VERBOSE_LEVEL - level of -v for runtime messages (def.: 1) e.g. 1 = -v -v is necessary to print info messages of the runtime system 2 = -v -v -v is necessary to print info messages of the runtime system Note: You can also set this environment variable before starting the script __QUIET_MODE - do not print messages to STDOUT (def.: false) use the parameter -q/+q to change this variable Note: You can also set this environment variable before starting the script __VERBOSE_MODE - print verbose messages (def.: false) use the parameter -v/+v to change this variable Note: You can also set this environment variable before starting the script __NO_TIME_STAMPS - Do not use time stamps in the messages (def.: false) Note: You can also set this environment variable before starting the script __NO_HEADERS - Do not print headers and footers (def.: false) Note: You can also set this environment variable before starting the script __FORCE - do the action anyway (def.: false) use the parameter -f/+f to change this variable __USE_COLORS - use colors (def.: false) use the parameter -a/+a to change this variable Note: You can also set this environment variable before starting the script __USER_BREAK_ALLOWED - CTRL-C aborts the script or not (def.: true) (no parameter to change this variable) Note: You can also set this environment variable before starting the script __NOECHO - turn echo off while reading input from the user do not echo the user input in AskUser if __NOECHO is set to ${__TRUE} __USE_TTY - write prompts and read user input from /dev/tty (def.: false) If __USE_TTY is ${__TRUE} the function AskUser writes the prompt to /dev/tty and the reads the user input from /dev/tty . This is useful if STDOUT is redirected to a file. __OVERWRITE mode - overwrite existing files or not (def.: false) use the parameter -O/+O to change this variable Note: You can also set this environment variable before starting the script __TEMPDIR - directory for temporary files The default is $TMPDIR (if defined), or $TMP (if defined), or $TEMP (if defined) or /tmp if none of the variables is defined __NO_OF_TEMPFILES number of automatically created tempfiles that are deleted at script end (def. 2) Note: The variable names for the tempfiles are __TEMPFILE1, __TEMPFILE2, etc. __TEMPFILE_UMASK umask for creating temporary files (def.: 177) __LIST_OF_TMP_MOUNTS - list of mounts that should be umounted at script end __LIST_OF_TMP_DIRS - list of directories that should be removed at script end __LIST_OF_TMP_FILES - list of files that should be removed at script end __SYSCMDS - list of commands execute via one of the execute... functions __SYSCMDS_FILE - write the list of executed commands via the execute.. functions to this file at script and __EXITROUTINES - list of routines that should be executed before the script ends Note: These routines are called *before* temporary files, temporary directories, and temporary mounts are removed Use "function_name:parameter1[[...]:parameter#] to add parameter for a function blanks or tabs in the parameter are NOT allowed __INSIDE_EXIT_ROUTINE is set to ${__TRUE} before calling a exit routine __FINISHROUTINES - list of routines that should be executed before the script ends Note: These routines are called *after* temporary files, temporary directories, and temporary mounts are removed Use "function_name:parameter1[[...]:parameter#] to add parameter for a function blanks or tabs in the parameter are NOT allowed __INSIDE_FINISH_ROUTINE is set to ${__TRUE} before calling a finish routine __PROCS_TO_KILL - list of proceesses to kill at script end Note: The processes are killed after the functions from __EXITROUTINES are executed To change the timeout after the "kill" command before issueing a "kill -9" for a specific process use "pid:timeout_in_seconds"; to disable "kill -9" for a specific process use "pid:-1" __PROCS_KILL_TIMEOUT - timeout in seconds to wait after the command "kill PID" in the function cleanup. If the PID is then still running it will be killed with the command "kill -9 PID" Use "-1" to disable the "kill -9" for all PIDs __GENERAL_SIGNAL_FUNCTION - name of the function to execute if a signal is received default signal handling: none This variable can be used to define a general user defined signal handler for all signals catched. If this signal handler is defined it will be called first for every signal. If the handler returns 0 the user defined signal handler for the signal will be called (if defined). If the handler returns a value other than 0 no other signal handler is called. see USER_SIGNAL_HANDLER for an example user signal handler __SIGNAL_SIGUSR1_FUNCTION - name of the function to execute if the signal SIGUSR1 is received default signal handling: create variable dump If a user defined function ends with a return code not equal zero the default action for the SIGUSR1 signal is not executed. see USER_SIGNAL_HANDLER for an example user signal handler __SIGNAL_SIGUSR2_FUNCTION - name of the function to execute if the signal SIGUSR2 is received default signal handling: call an interactive shell (experimental!) If a user defined function ends with a return code not equal zero the default action for the SIGUSR2 signal is not executed. see USER_SIGNAL_HANDLER for an example user signal handler __SIGNAL_SIGHUP_FUNCTION - name of the function to execute if the signal SIGHUP is received default signal handling: switch verbose mode on or off If a user defined function ends with a return code not equal zero the default action for the SIGHUP signal is not executed. see USER_SIGNAL_HANDLER for an example user signal handler __SIGNAL_SIGINT_FUNCTION - name of the function to execute if the signal SIGINT is received default signal handling: end the script if ${__USER_BREAK_ALLOWED} is ${__TRUE} else ignore the signal If a user defined function ends with a return code not equal zero the default action for the SIGINT signal is not executed. see USER_SIGNAL_HANDLER for an example user signal handler __IN_BREAK_HANDLER - this variable is true if we are in the signal handler for CTLR-C __CONTINUE_SCRIPT_EXECUTION can be set by the CTRL-C handler to temporary disable CTRL-C The signal handler will reset the variable to ${__FALSE} again __IN_DEBUG_SHELL is set to ${__TRUE} if the function DebugShell is active __SIGNAL_SIGQUIT_FUNCTION - name of the function to execute if the signal SIGQUIT is received default signal handling: end the script If a user defined function ends with a return code not equal zero the default action for the SIGQUIT signal is not executed. see USER_SIGNAL_HANDLER for an example user signal handler __SIGNAL_SIGTERM_FUNCTION - name of the function to execute if the signal SIGTERM is received default signal handling: end the script If a user defined function ends with a return code not equal zero the default action for the SIGTERM signal is not executed. see USER_SIGNAL_HANDLER for an example user signal handler __REBOOT_REQUIRED - set to true to reboot automatically at script end (def.: false) Note: To use this feature it must be enabled in the function RebootIfNecessary! __REBOOT_PARAMETER - parameter for the reboot command (def.: none) __DEBUG_PREFIX - prefix for debug messages printed with LogDebugMsg default: "DEBUG: " __INFO_PREFIX - prefix for INFO messages printed if __VERBOSE_MODE = ${__TRUE} default: "INFO: " __WARNING_PREFIX - prefix for WARNING messages default: "WARNING: " __ERROR_PREFIX - prefix for ERROR messages default: "ERROR: " __RUNTIME_INFO_PREFIX - prefix for INFO messages of the runtime system default: "RUNTIME INFO: " __PRINT_LIST_OF_WARNINGS_MSGS - print the list of warning messages at script end (def.: false) Note: Do not change this variable direct -- change __PRINT_SUMMARIES instead __PRINT_LIST_OF_ERROR_MSGS - print the list of error messages at script end (def.: false) Note: Do not change this variable direct -- change __PRINT_SUMMARIES instead __PRINT_SUMMARIES - print error/warning msg summaries at script end print error and/or warning message summaries at script end known values: 0 = do not print summaries 1 = print error msgs 2 = print warning msgs 3 = print error and warning mgs use the parameter -S to change this variable __MAINRC - return code of the program ##### defined variables that should not be changed __CONFIG_FILE - name of the default config file (use ReadConfigFile to read the config file; use WriteConfigFile to write it) use none to disable the config file feature __PIDFILE - save the pid of the script in a file if this variable is defined example usage: __PIDFILE="/tmp/${__SCRIPTNAME%.*}.pid" __HOSTNAME - hostname __NODENAME - nodename __OS_FULLNAME - Operating system (e.g. CYGWIN_NT-5.1) __ZONENAME - name of the current zone if running in Solaris 10 or newer __OS_VERSION - Operating system version (e.g 5.8) __OS_RELEASE - Operating system release (e.g. Generic_112233-08) __MACHINE_CLASS - Machine class (e.g sun4u) __MACHINE_SUB_CLASS - Machine sub class either GuestLDom or PrimaryLDom for sun4v LDoms __MACHINE_PLATFORM - hardware platform (e.g. SUNW,Ultra-4) __MACHINE_SUBTYPE - machine type (e.g Sun Fire 3800) __MACHINE_ARC - machine architecture (e.g. sparc) __RUNLEVEL - current runlevel __START_DIR - working directory when starting the script (may be a symbolic link) __START_DIR_REAL - working directory when starting the script (symbolic links resolved) __LOGFILE - fully qualified name of the logfile used use the parameter -l to change the logfile in Solaris /tmp is mounted on a RAM disk so we check if /var/tmp exists first LOGMSG_FUNCTION - function to write log messages to STDOUT or STDERR default: use "echo " to write in log functions __NO_OF_WARNINGS - Number of warnings found __LIST_OF_WARNINGS - List of warning messages __NO_OF_ERRORS - Number of errors found __LIST_OF_ERRORS - List of error messages __LOGIN_USERID - ID of the user opening the session __USERID - ID of the user executing this script (e.g. xtrnaw7) Foreground Color variables: __COLOR_FG_BLACK, __COLOR_FG_RED, __COLOR_FG_GREEN, __COLOR_FG_YELLOW __COLOR_FG_BLUE, __COLOR_FG_MAGENTA, __COLOR_FG_CYAN, __COLOR_FG_WHITE Background Color variables: __COLOR_BG_BLACK, __COLOR_BG_RED, __COLOR_BG_GREEN, __COLOR_BG_YELLOW __COLOR_BG_BLUE, __COLOR_BG_MAGENTA, __COLOR_BG_CYAN, __COLOR_BG_WHITE Colorattributes: __COLOR_OFF, __COLOR_BOLD, __COLOR_NORMAL, - normal, __COLOR_UNDERLINE __COLOR_BLINK, __COLOR_REVERSE, __COLOR_INVISIBLE ##### defined sub routines -------------------------------------- ReadConfigFile read the config file usage: ReadConfigFile [configfile] where: configfile - name of the config file default: search ${__CONFIG_FILE} in the current directory, in the home directory, and in /etc (in this order) returns: ${__TRUE} - ok config read ${__FALSE} - error config file not found or not readable -------------------------------------- WriteConfigFile write the variable ${__CONFIG_PARAMETER} to the config file usage: WriteConfigFile [configfile] where: configfile - name of the config file default: write ${__CONFIG_FILE} in the current directory returns: ${__TRUE} - ok config file written ${__FALSE} - error writing the config file -------------------------------------- NoOfStackElements return the number of stack elements usage: NoOfStackElements; var=$? returns: number of elements on the stack Note: NoOfStackElements, FlushStack, push and pop use only one global stack! -------------------------------------- FlushStack flush the stack usage: FlushStack returns: number of elements on the stack before flushing it Note: NoOfStackElements, FlushStack, push and pop use only one global stack! In the current implementation the stack routines only support up to 255 Stack elements -------------------------------------- push push one or more values on the stack usage: push value1 [...] [value#] returns: 0 Note: NoOfStackElements, FlushStack, push and pop use only one global stack! In the current implementation the stack routines only support up to 255 Stack elements -------------------------------------- pop pop one or more values from the stack usage: pop variable1 [...] [variable#] returns: 0 Note: NoOfStackElements, FlushStack, push and pop use only one global stack! In the current implementation the stack routines only support up to 255 Stack elements -------------------------------------- push_and_set push a variable to the stack and set the variable to a new value usage: push_and_set variable new_value returns: 0 Note: NoOfStackElements, FlushStack, push and pop use only one global stack! In the current implementation the stack routines only support up to 255 Stack elements -------------------------------------- CheckYNParameter check if a parameter is y, n, 0, or 1 usage: CheckYNParameter parameter returns: ${__TRUE} - the parameter is equal to yes ${__FALSE} - the parameter is equal to no -------------------------------------- ConvertToYesNo convert the value of a variable to y or n usage: ConvertToYesNo parameter returns: 0 prints y, n or ? to STDOUT -------------------------------------- InvertSwitch invert a switch from true to false or vice versa usage: InvertSwitch variable returns 0 switch the variable "variable" from ${__TRUE} to ${__FALSE} or vice versa -------------------------------------- CheckInputDevice check if the input device is a terminal usage: CheckInputDevice returns: 0 - the input device is a terminal (interactive) 1 - the input device is NOT a terminal -------------------------------------- GetProgramDirectory get the directory where a program resides usage: GetProgramDirectory [programpath/]programname [resultvar] returns: 0 the variable PRGDIR contains the directory with the program if the parameter resultvar is missing -------------------------------------- substr get a substring of a string usage: variable=$( substr sourceStr pos length ) or substr sourceStr pos length resultVariable returns: 1 - parameter missing 0 - parameter okay -------------------------------------- replacestr replace a substring with another substring usage: variable=$( replacestr sourceStr oldsubStr newsubStr ) or replacestr sourceStr oldsubStr newsubStr resultVariable returns: 0 - substring replaced 1 - substring not found 3 - error, parameter missing writes the substr to STDOUT if resultvariable is missing -------------------------------------- pos get the first position of a substring in a string usage: pos searchstring sourcestring returns: 0 - searchstring is not part of sourcestring else the position of searchstring in sourcestring -------------------------------------- lastpos get the last position of a substring in a string usage: lastpos searchstring sourcestring returns: 0 - searchstring is not part of sourcestring else the position of searchstring in sourcestring -------------------------------------- isNumber check if a value is an integer usage: isNumber testValue returns: ${__TRUE} - testValue is a number else not -------------------------------------- ConvertToHex convert the value of a variable to a hex value usage: ConvertToHex value returns: 0 prints the value in hex to STDOUT -------------------------------------- ConvertToOctal convert the value of a variable to a octal value usage: ConvertToOctal value returns: 0 prints the value in octal to STDOUT -------------------------------------- ConvertToBinary convert the value of a variable to a binary value usage: ConvertToBinary value returns: 0 prints the value in binary to STDOUT -------------------------------------- toUppercase convert a string to uppercase usage: toUppercase sourceString | read resultVariable or targetString=$( toUppercase sourceString ) or toUppercase sourceString resultVariable returns: 0 writes the converted string to STDOUT if resultString is missing -------------------------------------- toLowercase convert a string to lowercase usage: toLowercase sourceString | read resultVariable or targetString=$( toLowercase sourceString ) or toLowercase sourceString resultVariable returns: 0 writes the converted string to STDOUT if resultString is missing -------------------------------------- StartStop_LogAll_to_logfile redirect STDOUT and STDERR into a file usage: StartStop_LogAll_to_logfile [start|stop] logfile returns: 0 - okay, redirection started / stopped 1 - error, can not write to the logfile 2 - invalid usage (to much or not enough parameter) 3 - invalid parameter 4 - tracing is enabled To explicitly write to STDOUT after calling this function with the parameter "start" use echo "This goes to STDOUT" >&3 To explicitly write to STDERR after calling this function with the parameter "start" use echo "This goes to STDERR" >&4 -------------------------------------- executeCommand execute a command usage: executeCommand command parameter returns: the RC of the executed command -------------------------------------- executeCommandAndLog execute a command and write STDERR and STDOUT also to the logfile usage: executeCommandAndLog command parameter returns: the RC of the executed command (even if a logfile is used!) -------------------------------------- executeCommandAndLogSTDERR execute a command and write STDERR also to the logfile usage: executeCommandAndLogSTDERR command parameter returns: the RC of the executed command -------------------------------------- UserIsRoot validate the user id usage: UserIsRoot returns: ${__TRUE} - the user is root; else not -------------------------------------- UserIs validate the user id usage: UserIs USERID where: USERID - userid (e.g oracle) returns: 0 - the user is this user 1 - the user is NOT this user 2 - the user does not exist on this machine 3 - missing parameter -------------------------------------- GetCurrentUID get the UID of the current user usage: GetCurrentUID where: - returns: the function writes the UID to STDOUT -------------------------------------- GetUserName get the name of a user usage: GetUserName UID where: UID - userid (e.g 1686) returns: 0 __USERNAME contains the user name or "" if the userid does not exist on this machine -------------------------------------- GetUID get the UID for a username usage: GetUID username where: username - user name (e.g nobody) returns: 0 __USER_ID contains the UID or "" if the username does not exist on this machine -------------------------------------- PrintWithTimestamp print the output of a command to STDOUT with a timestamp usage: PrintWithTimestamp command_to_execute [parameter] returns: 0 Note: This function does not write to the log file! Source: in v2.x and newer http://unix.stackexchange.com/questions/26728/prepending-a-timestamp-to-each-line-of-output-from-a-command -------------------------------------- LogMsg print a message to STDOUT and write it also to the logfile usage: LogMsg message returns: ${__TRUE} - message printed ${__FALSE} - message not printed Notes: Use "- message" to suppress the date stamp Use "-" to print a complete blank line -------------------------------------- LogOnly write a message to the logfile usage: LogOnly message returns: ${__TRUE} - message printed ${__FALSE} - message not printed -------------------------------------- LogIfNotVerbose write a message to stdout and the logfile if we are not in verbose mode usage: LogIfNotVerbose message returns: ${__TRUE} - message printed ${__FALSE} - message not printed -------------------------------------- PrintDotToSTDOUT write a message to stdout only if we are not in verbose mode usage: PrintDotToSTDOUT [msg] default for msg is "." without a LF; use "\n" to print a LF returns: ${__TRUE} - message printed ${__FALSE} - message not printed -------------------------------------- LogInfo print a message to STDOUT and write it also to the logfile only if in verbose mode usage: LogInfo [loglevel] message returns: ${__TRUE} - message printed ${__FALSE} - message not printed Notes: Output goes to STDERR, default loglevel is 0 -------------------------------------- LogWarning print a warning to STDERR and write it also to the logfile usage: LogWarning message returns: ${__TRUE} - message printed ${__FALSE} - message not printed Notes: Output goes to STDERR -------------------------------------- LogDebugMsg print a debug message to STDERR and write it also to the logfile usage: LogDebugMsg message returns: ${__TRUE} - message printed ${__FALSE} - message not printed Notes: Output goes to STDERR -------------------------------------- LogError print an error message to STDERR and write it also to the logfile usage: LogError message returns: ${__TRUE} - message printed ${__FALSE} - message not printed Notes: Output goes to STDERR --------------------------------------- BackupFileIfNecessary create a backup of a file if ${__OVERWRITE_MODE} is set to ${__FALSE} usage: BackupFileIfNecessary [file1} ... {filen} file is the filename of the file to backup, format: filename[,no_of_backups] If no_of_backups is ommitted only one backup is created; the name of the backup is ${CURFILE}${BACKUP_EXTENSION} The default value for ${BACKUP_EXTENSION} is ".[pid]" If no_of_backups is specified for one file the functions keeps up to no_of_backup backups of the file and the name(s) of the backup files ${CURFILE}.0 ${CURFILE}.1 ${CURFILE}.2 ... ${CURFILE}.[no_of_backups - 1] returns: ${__TRUE} - done; ${__FALSE} - error creating a backup of the file ${__BACKUP_FILE_ERROR} The function returns after the first error; no backups will be created for the remaining files in the parameter If successfull ${__BACKUP_FILE} contains the name(s) of the backup file(s). If no backup was created ${__BACKUP_FILE} is empty --------------------------------------- CopyDirectory copy a directory usage: CopyDirectory sourcedir targetDir returns: 0 - done; else error -------------------------------------- DebugShell Open a simple debug shell Usage: DebugShell returns: ${__TRUE} Input is always read from /dev/tty; output always goes to /dev/tty -------------------------------------- AskUser Ask the user (or use defaults depending on the parameter -n and -y) Usage: AskUser "message" returns: ${__TRUE} - user input is yes ${__FALSE} - user input is no USER_INPUT contains the user input Notes: "all" is interpreted as yes for this and all other questions "none" is interpreted as no for this and all other questions If __NOECHO is ${__TRUE} the user input is not written to STDOUT __NOECHO is set to ${__FALSE} again in this function If __USE_TTY is ${__TRUE} the prompt is written to /dev/tty and the user input is read from /dev/tty . This is useful if STDOUT is redirected to a file. "shell" opens the DebugShell; set __DEBUG_SHELL_IN_ASKUSER to ${__FALSE} to disable the DebugShell in AskUser -------------------------------------- GetKeystroke read one key from STDIN Usage: GetKeystroke [upper|lower] "message" returns: 0 USER_INPUT contains the user input (converted to uppercase or lowercase if requested) RAW_USER_INPUT contains unconverted user input Sample key codes in RAW_USER_INPUT : $'\E' ESC $'\r' RETURN or CTRL-M $'\f' CTRL-L $'\a' CTRL-G $'\b' CTRL-H $'\t' TAB or CTRL-I $'\x01' CTRL-A $'\x02' CTRL-B $'\x03' CTRL-C $'\x04' CTRL-E $'\x05' CTRL-F $'\x06' CTRL-G $'\x0b' CTRL-K $'\x0e' CTRL-N $'\x0f' CTRL-O $'\x10' CTRL-P ... $'\x15' CTRL-U ... $'\x1a' CTRL-Z $'\E[5~' PageUp $'\E[6~' PageDown $'\E[B' CursorDown $'\E[A' CursorUp $'\E[D' CursorLeft $'\E[C' CursorRight $'\EOH' Home $'\EOF' End $'\E[2~' Insert $'\E[3~' Delete $'\E[4~' End (Numblock) $'\E[1~' Home (Numblock) $'\E[E' 5 (Numblock, NumOff) -------------------------------------- RebootIfNecessary Check if a reboot is necessary Usage: RebootIfNecessary Notes The routine asks the user if neither the parameter -y nor the parameter -n is used Before using this routine uncomment the reboot command! --------------------------------------- die print a message and end the program usage: die returncode {message} returns: $1 (if it returns) Notes: This routine - calls cleanup - prints an error message if any (if returncode is not zero) or the message if any (if returncode is zero) - prints all warning messages again if ${__PRINT_LIST_OF_WARNING_MSGS} is ${__TRUE} - prints all error messages again if ${__PRINT_LIST_OF_ERROR_MSGS} is ${__TRUE} - prints a script end message and the program return code and - and ends the program or reboots the machine if requested --------------------------------------- tryIncludeScript include a script via . [scriptname] if it exists and is error free usage: tryIncludeScript [scriptname] returns: $? after including the script if the script was executed else 0 Ouptut variables: __INCLUDE_SCRIPT_CHECK_OUTPUT= __INCLUDE_SCRIPT_RC - result code; known values: 0 - script found, checked, and executed 1 - script not found 2 - script has syntax errors 3 - tryIncludeScript called without parameter notes: first check the variable __INCLUDE_SCRIPT_RC then the return code! --------------------------------------- includeScript include a script via . [scriptname] usage: includeScript [scriptname] returns: $? after including the script if the script was executed notes: includeScript aborts the script via die() if the include file does not exist or has syntax errors --------------------------------------- executeFunctionIfDefined execute a function if it's defined usage: executeFunctionIfDefined [function_name] {function_parameter} returns: the RC of the function [function_name] or 255 if the function is not defined notes: -------------------------------------- rand print a random number to STDOUT usage: rand returns: ${__TRUE} - random number printed to STDOUT ${__FALSE} - can not create a random number notes: This function prints the contents of the environment variable RANDOM to STDOUT. If that variable is not defined, it uses nawk to create a random number. If nawk is not available the function prints nothng to STDOUT ##### defined internal sub routines (do NOT use; these routines are called by the runtime system!) PrintLockFileErrorMsg CreateLockFile RemoveLockFile CreateTemporaryFiles --------------------------------------- cleanup -------------------------------------- CreateDump save the current environment of the script usage: CreateDump [targetdir] [filename_add] returns: ${__TRUE} - ok, dump created (or dump was already created) ${__FALSE} - error creating the dump ##### defined trap handler (you may change them) --------------------------------------- IsFunctionDefined check if a function is defined in this script usage: IsFunctionDefined name_of_the_function returns: ${__TRUE} - the function is defined ${__FALSE} - the function is not defined --------------------------------------- GENERAL_SIGNAL_HANDLER general trap handler usage: called automatically; parameter: $1 = signal number $2 = LineNumber $3 = function name returns: - --------------------------------------- InitScript init the script runtime usage: [called by the runtime system] returns: 0 --------------------------------------- SetEnvironment set and check the environment usage: [called by the runtime system] returns: 0 ##### defined sub routines --------------------------------------- ShowShortUsage print the (short) usage help usage: ShowShortUsage returns: 0 --------------------------------------- ShowUsage print the (long) usage help usage: ShowUsage returns: 0 -------------------------------------- SetHousekeeping do or do not house keeping (remove tmp files/directories; execute exit routines/finish routines) at script end usage: SetHousekeeping [${__TRUE}|${__FALSE}] parameter: ${__TRUE} | all - do house keeping ${__FALSE} | none - no house keeping nodelete - do all house keeping except removing temporary files and directories returns: 0 - okay 1 - invalid usage -------------------------------------- PrintRuntimeVariables print the values of the runtime variables usage: PrintRuntimeVariables returns: ${__TRUE} - ok ${__FALSE} - error else - invalid usage other subroutines that can be used in your code -------------------------------------- GetOtherDate get the date for today +/- n ( 1 <= n <= 6) usage: GetOtherDate [+|-]no_of_days [format] where +/-no_of_days - relative date (e.g -1, -2, etc) format - format for the date (def.: %Y-%m-%d) returns: writes the date to STDOUT notes: - = date in the future + = date in the past max. date difference : +/- 6 days This function was only tested successfull in Solaris! -------------------------------------- ConvertDateToEpoc convert a date into epoc time usage: ConvertDateToEpoc [day month year hours minutes seconds] {diff} returns: ${__TRUE} - ok ${__FALSE} - error The epoc time is printed to STDOUT -------------------------------------- GetTimeStamp get the current time stamp in the format dd:mm:yyyy hh:mm usage: GetTimeStamp returns: ${__TRUE} - ok ${__FALSE} - error The timestamp is printed to STDOUT -------------------------------------- GetSeconds get the seconds since 1970-01-01 00:00:00 UTC usage: GetSeconds returns: ${__TRUE} - ok ${__FALSE} - error The seconds are printed to STDOUT -------------------------------------- GetMinutes get the minutes since 1970-01-01 00:00:00 UTC usage: GetMinutes returns: ${__TRUE} - ok ${__FALSE} - error The minutes are printed to STDOUT -------------------------------------- ConvertMinutesToHours convert a number of minutes in hh:mm usage: ConvertMinutesToHours returns: ${__TRUE} - ok ${__FALSE} - error The result is printed to STDOUT -------------------------------------- SaveEnvironmentVariables save selected environment variables to a file usage: SaveEnvironmentVariables filename [[pattern1]...[pattern#]] where: filename - name of the file for the environment variables pattern# - egrep pattern to select the environment variables to save returns: ${__TRUE} - ok ${__FALSE} - error Notes: To reuse the file later use the function includeScript -------------------------------------- PrintLine print a line with n times the character c usage: PrintLine [n] {c} {msg} returns: ${__TRUE} - ok ${__FALSE} - error default for c is "-" -------------------------------------- list_returncodes list all return codes used by a script usage: list_returncodes {scriptname} returns: the functions prints a list of all returncodes to STDOUT This works only if only the function die is used to end the script. -------------------------------------- ProcessDebugSwitch process the debug switches usage: ProcessDebugSwitch debugswitch returns: ${__TRUE} - ok ${__FALSE} - error -------------------------------------- print_runtime_variables print some usage examples for the functions defined in the template to STDOUT usage: print_runtime_variables returns: ${__TRUE} - ok ${__FALSE} - error -------------------------------------- PrintScriptEnv print a short list of the environment usage: PrintScriptEnv returns: ${__TRUE} - ok ${__FALSE} - error -------------------------------------- SyntaxHelp print some usage examples for the functions defined in the template to STDOUT usage: SyntaxHelp returns: ${__TRUE} - ok ${__FALSE} - error -------------------------------------- USER_SIGNAL_HANDLER template for a user defined trap handler usage: to define one signal handler for all signals do: __GENERAL_SIGNAL_FUNCTION=USER_SIGNAL_HANDLER to define unique signal handler for the various signals do: __SIGNAL__FUNCTION="USER_SIGNAL_HANDLER" e.g.: __SIGNAL_SIGUSR1_FUNCTION=USER_SIGNAL_HANDLER __SIGNAL_SIGUSR2_FUNCTION=USER_SIGNAL_HANDLER __SIGNAL_SIGHUP_FUNCTION=USER_SIGNAL_HANDLER __SIGNAL_SIGINT_FUNCTION=USER_SIGNAL_HANDLER __SIGNAL_SIGQUIT_FUNCTION=USER_SIGNAL_HANDLER __SIGNAL_SIGTERM_FUNCTION=USER_SIGNAL_HANDLER returns: 0 - execute the next action for this signal else - do not execute the next action for this signal Notes: Depending on the return code of the signal handler the other signal handler are called (RC=0) or not (RC<>0) The call order is - general user defined signal handler (if defined) - signal specific user defined signal handler (if defined) - default specific signal handler -------------------------------------- YourRoutine template for a user defined function usage: YourRoutine returns: ${__TRUE} - ok ${__FALSE} - error ----------------------------------------------------------------------------- Note: Use ./scriptt.sh -D SyntaxHelp 2>./scriptt.sh.syntaxhelp to get some syntax examples for the functions defined in the template. -----------------------------------------------------------------------------