----------------------------------------------------------------------------------------------------- scriptt.sh v0.0.1 (Scripttemplate: 1.22.46 27.04.2013) 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 and others Description ----------- ??? Configuration file ------------------ This script supports a configuration file called .conf. The configuration file is searched 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. Predefined parameter -------------------- see the subroutines ShowShortUsage and ShowUsage Note: The current version of the script template can be found here: http://bnsmb.de/solaris/scriptt.html Troubleshooting support ----------------------- 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 directory /var/tmp/debug 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 export __DUMPDIR=/var/tmp/debug ./scriptt.sh To suppress creating the dump file in case of a syntax error use __DUMP_ALREADY_CREATED=0 Use CreateDump [filename_add] to manually create the dump files. 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 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. Credits ------- wpollock (http://wikis.sun.com/display/~wpollock) -- http://wikis.sun.com/display/BigAdmin/A+Script+Template+and+Useful+Techniques+for+ksh+Scripts?focusedCommentId=12517624#comment-12517624 Source for the function PrintWithTimeStamp: Bernd Fingers blog: http://blogs.sun.com/blogfinger/entry/prepend_command_output_lines_with 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 History: -------- ??.??.2009 v0.0.0.1 /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 an spelling error (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 ---------------- Version variables __SCRIPT_VERSION - the version of your script __SCRIPT_TEMPLATE_VERSION - version of the script template ---------------- Predefined return codes: ------------------------ 1 - show usage and exit 2 - invalid parameter found 210 - 235 reserved for the runtime system 236 - syntax error 237 - script file has too many lines for the debug handler 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 __WARNING_PREFIX __ERROR_PREFIX __RUNTIME_INFO_PREFIX __DEBUG_HISTFILE __NO_CLEANUP __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) ##### constants __TRUE - true (0) __FALSE - false (1) __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 __OS - Operating system (e.g. SunOS) __SHELL - name of the current shell executing this script ---------------- internal variables __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 __FUNCTION_INIT - code executed at start of every sub routine (see the hints for __DEBUG_CODE) Default init code : install the trap handlers __NO_EXIT_ROUTINES - do not execute the exit routines 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 sample debug code: __DEBUG_CODE=" eval echo Entering the subroutine \${__FUNCTION} ... " Note: Use an include script for more complicate debug code, e.g. __DEBUG_CODE=" eval . /var/tmp/mydebugcode" __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 her __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 __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} __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 __REQUIRED_ZONES - required zones (either global, non-global or local or the names of the valid zones) (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) If this variable is set to ${__TRUE} the function "die" will return if called with an RC not zero (instead of aborting the script) 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 __DEBUG_MODE - use single step mode for main (def.: false) use the parameter -D/+D to change this variable __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 program 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 program end __LIST_OF_TMP_DIRS - list of directories that should be removed at program end __LIST_OF_TMP_FILES - list of files that should be removed at program end __EXITROUTINES - list of routines that should be executed before the script ends Note: These routines are called *before* temp files, temp directories, and temp mounts are removed __FINISHROUTINES - list of routines that should be executed before the script ends Note: These routines are called *after* temp files, temp directories, and temp mounts are removed __SIGNAL_SIGUSR1_FUNCTION - name of the function to execute if the signal SIGUSR1 is received default signal handling: none 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: none 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 the 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 __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) __REBOOT_PARAMETER - parameter for the reboot command (def.: none) __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 program end (def.: false) __PRINT_LIST_OF_ERROR_MSGS - print the list of error messages at program end (def.: false) __PRINT_SUMMARIES - print error/warning msg summaries at script end print error and/or warning message summaries at program 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 __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) __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 example usage: __PIDFILE="/tmp/${__SCRIPTNAME%.*}.pid" __HOSTNAME - hostname __NODENAME - nodename __OS_FULLNAME - Operating system (e.g. CYGWIN_NT-5.1) (only used for CYGWIN at this time) __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_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 __LOGFILE - fully qualified name of the logfile used use the parameter -l to change the logfile LOGMSG_FUNCTION - function to write log messages default: use "echo " to write 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 __LOGON_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 no. of stack elements usage: NoOfStackElements; var=$? returns: no. of elements on the stack Note: NoOfStackElements, FlushStack, push and pop use only one global stack! -------------------------------------- FlushStack flush the stack usage: FlushStack returns: no. of elements on the stack before flushing it Note: NoOfStackElements, FlushStack, push and pop use only one global stack! -------------------------------------- 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! -------------------------------------- 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! -------------------------------------- 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! -------------------------------------- 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 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 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 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: Bernd Fingers blog: http://blogs.sun.com/blogfinger/entry/prepend_command_output_lines_with -------------------------------------- LogMsg print a message to STDOUT and write it also to the logfile usage: LogMsg message returns: 0 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: 0 -------------------------------------- LogIfNotVerbose write a message to stdout and the logfile if we are not in verbose mode usage: LogIfNotVerbose message returns: 0 -------------------------------------- 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: 0 -------------------------------------- LogInfo print a message to STDOUT and write it also to the logfile only if in verbose mode usage: LogInfo [loglevel] message returns: 0 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: 0 Notes: Output goes to STDERR -------------------------------------- LogError print an error message to STDERR and write it also to the logfile usage: LogError message returns: 0 Notes: Output goes to STDERR --------------------------------------- BackupFileIfNecessary create a backup of a file if ${__OVERWRITE_MODE} is set to ${__FALSE} usage: BackupFileIfNecessary [file1} ... {filen} returns: 0 - done; else error --------------------------------------- CopyDirectory copy a directory usage: CopyDirectory sourcedir targetDir returns: 0 - done; else error -------------------------------------- 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. -------------------------------------- GetKeystroke read one key from STDIN Usage: GetKeystroke "message" returns: 0 USER_INPUT contains the user input -------------------------------------- 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 program end message and the program return code and - and ends the program or reboots the machine if requested If the variable ${__FORCE} is ${__TRUE} and the return code is NOT zero die() will only print the error message and return --------------------------------------- includeScript include a script via . [scriptname] usage: includeScript [scriptname] returns: 0 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 house keeping at program end usage: [called by the runtime system] returns: 0 notes: execution order is - call exit routines from ${__EXITROUTINES} - remove files from ${__LIST_OF_TMP_FILES} - umount mount points ${__LIST_OF_TMP_MOUNTS} - remove directories ${__LIST_OF_TMP_DIRS} - call finish routines from ${__FINISHROUTINES} -------------------------------------- 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) --------------------------------------- GENERAL_SIGNAL_HANDLER general trap handler usage: called automatically; parameter: $1 = signal number $2 = LineNumber $3 = function name returns: - notes: see USER_SIGNAL_HANDLER for an example user signal handler --------------------------------------- DebugHandler handler for single step mode usage: called automatically returns: the RC of the previous executed command --------------------------------------- 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 -------------------------------------- CheckParameterCount check the number of parameters for a function usage: CheckParameterCount parametercount "$@" returns: ${__TRUE} - the no of parameter is ok ${__FALSE} - the no of parameter is not ok --------------------------------------- ShowShortUsage print the (short) usage help usage: ShowShortUsage returns: 0 --------------------------------------- ShowUsage print the (long) usage help usage: ShowUsage returns: 0 -------------------------------------- USER_SIGNAL_HANDLER sample user defined trap handler usage: __SIGNAL__FUNCTION="USER_SIGNAL_HANDLER" e.g. __SIGNAL_SIGUSR1_FUNCTION="USER_SIGNAL_HANDLER" returns: 0 - execute the default action for this signal else - do not execute the default action for this signal -------------------------------------- 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} - do house keeping ${__FALSE} - no house keeping 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! -------------------------------------- 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 template for a user defined trap handler -------------------------------------- USER_SIGNAL_HANDLER sample user defined trap handler usage: __SIGNAL__FUNCTION="USER_SIGNAL_HANDLER" e.g. __SIGNAL_SIGUSR1_FUNCTION="USER_SIGNAL_HANDLER" returns: 0 - execute the default action for this signal else - do not execute the default action for this signal template for a new user function -------------------------------------- YourRoutine template for a user defined function usage: YourRoutine returns: ${__TRUE} - ok ${__FALSE} - error