1 if [ ! "$_COMMON_SUBR" ]; then _COMMON_SUBR=1
3 # Copyright (c) 2012 Ron McDowell
4 # Copyright (c) 2012-2013 Devin Teske
7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions
10 # 1. Redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer.
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in the
14 # documentation and/or other materials provided with the distribution.
16 # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 ############################################################ CONFIGURATION
33 # Default file descriptors to link to stdout/stderr for passthru allowing
34 # redirection within a sub-shell to bypass directly to the terminal.
36 : ${TERMINAL_STDOUT_PASSTHRU:=3}}
37 : ${TERMINAL_STDERR_PASSTHRU:=4}}
39 ############################################################ GLOBALS
53 # Global exit status variables
59 # Operating environment details
61 export UNAME_S="$( uname -s )" # Operating System (i.e. FreeBSD)
62 export UNAME_P="$( uname -p )" # Processor Architecture (i.e. i386)
63 export UNAME_M="$( uname -m )" # Machine platform (i.e. i386)
64 export UNAME_R="$( uname -r )" # Release Level (i.e. X.Y-RELEASE)
65 if [ ! "${PKG_ABI+set}" ]; then
67 ASSUME_ALWAYS_YES=1 pkg -vv 2> /dev/null |
68 awk '$1=="ABI"{print $3;exit}'
73 # Default behavior is to call f_debug_init() automatically when loaded.
75 : ${DEBUG_SELF_INITIALIZE=1}
78 # Default behavior of f_debug_init() is to truncate $debugFile (set to NULL to
79 # disable truncating the debug file when initializing). To get child processes
80 # to append to the same log file, export this variarable (with a NULL value)
81 # and also export debugFile with the desired value.
83 : ${DEBUG_INITIALIZE_FILE=1}
86 # Define standard optstring arguments that should be supported by all programs
87 # using this include (unless DEBUG_SELF_INITIALIZE is set to NULL to prevent
88 # f_debug_init() from autamatically processing "$@" for the below arguments):
91 # D: Sets $debugFile to $OPTARG
96 # The getopts builtin will return 1 either when the end of "$@" or the first
97 # invalid flag is reached. This makes it impossible to determine if you've
98 # processed all the arguments or simply have hit an invalid flag. In the cases
99 # where we want to tolerate invalid flags (f_debug_init() for example), the
100 # following variable can be appended to your optstring argument to getopts,
101 # preventing it from prematurely returning 1 before the end of the arguments.
103 # NOTE: This assumes that all unknown flags are argument-less.
105 GETOPTS_ALLFLAGS="abcdefghijklmnopqrstuvwxyz"
106 GETOPTS_ALLFLAGS="${GETOPTS_ALLFLAGS}ABCDEFGHIJKLMNOPQRSTUVWXYZ"
107 GETOPTS_ALLFLAGS="${GETOPTS_ALLFLAGS}0123456789"
110 # When we get included, f_debug_init() will fire (unless $DEBUG_SELF_INITIALIZE
111 # is set to disable automatic initialization) and process "$@" for a few global
112 # options such as `-d' and/or `-D file'. However, if your program takes custom
113 # flags that take arguments, this automatic processing may fail unexpectedly.
115 # The solution to this problem is to pre-define (before including this file)
116 # the following variable (which defaults to NULL) to indicate that there are
117 # extra flags that should be considered when performing automatic processing of
118 # globally persistent flags.
122 ############################################################ FUNCTIONS
124 # f_dprintf $format [$arguments ...]
126 # Sensible debug function. Override in ~/.bsdconfigrc if desired.
127 # See /usr/share/examples/bsdconfig/bsdconfigrc for example.
129 # If $debug is set and non-NULL, prints DEBUG info using printf(1) syntax:
130 # + To $debugFile, if set and non-NULL
131 # + To standard output if $debugFile is either NULL or unset
132 # + To both if $debugFile begins with a single plus-sign (`+')
136 [ "$debug" ] || return $SUCCESS
137 local fmt="$1"; shift
138 case "$debugFile" in ""|+*)
139 printf "DEBUG: $fmt${fmt:+\n}" "$@" >&${TERMINAL_STDOUT_PASSTHRU:-1}
141 [ "${debugFile#+}" ] &&
142 printf "DEBUG: $fmt${fmt:+\n}" "$@" >> "${debugFile#+}"
148 # Initialize debugging. Truncates $debugFile to zero bytes if set.
153 # Process stored command-line arguments
157 f_dprintf "f_debug_init: ARGV=[%s] GETOPTS_STDARGS=[%s]" \
158 "$ARGV" "$GETOPTS_STDARGS"
159 while getopts "$GETOPTS_STDARGS$GETOPTS_EXTRA$GETOPTS_ALLFLAGS" flag \
163 D) debugFile="$OPTARG" ;;
166 shift $(( $OPTIND - 1 ))
167 f_dprintf "f_debug_init: debug=[%s] debugFile=[%s]" \
168 "$debug" "$debugFile"
171 # Automagically enable debugging if debugFile is set (and non-NULL)
173 [ "$debugFile" ] && { [ "${debug+set}" ] || debug=1; }
176 # Make debugging persistant if set
178 [ "$debug" ] && export debug
179 [ "$debugFile" ] && export debugFile
182 # Truncate debug file unless requested otherwise. Note that we will
183 # trim a leading plus (`+') from the value of debugFile to support
184 # persistant meaning that f_dprintf() should print both to standard
185 # output and $debugFile (minus the leading plus, of course).
187 local _debug_file="${debugFile#+}"
188 if [ "$_debug_file" -a "$DEBUG_INITIALIZE_FILE" ]; then
189 if ( umask 022 && :> "$_debug_file" ); then
190 f_dprintf "Successfully initialized debugFile \`%s'" \
192 f_isset debug || debug=1 # turn debugging on if not set
195 f_dprintf "Unable to initialize debugFile \`%s'" \
201 # f_err $format [$arguments ...]
203 # Print a message to stderr (fd=2).
210 # f_quietly $command [$arguments ...]
212 # Run a command quietly (quell any output to stdout or stderr)
216 "$@" > /dev/null 2>&1
219 # f_have $anything ...
221 # A wrapper to the `type' built-in. Returns true if argument is a valid shell
222 # built-in, keyword, or externally-tracked binary, otherwise false.
229 # f_which $anything [$var_to_set]
231 # A fast built-in replacement for syntaxes such as foo=$( which bar ). In a
232 # comparison of 10,000 runs of this function versus which, this function
233 # completed in under 3 seconds, while `which' took almost a full minute.
235 # If $var_to_set is missing or NULL, output is (like which) to standard out.
236 # Returns success if a match was found, failure otherwise.
240 local __name="$1" __var_to_set="$2"
241 case "$__name" in */*|'') return $FAILURE; esac
242 local __p IFS=":" __found=
244 local __exec="$__p/$__name"
245 [ -f "$__exec" -a -x "$__exec" ] && __found=1 && break
247 if [ "$__found" ]; then
248 if [ "$__var_to_set" ]; then
249 setvar "$__var_to_set" "$__exec"
258 # f_getvar $var_to_get [$var_to_set]
260 # Utility function designed to go along with the already-builtin setvar.
261 # Allows clean variable name indirection without forking or sub-shells.
263 # Returns error status if the requested variable ($var_to_get) is not set.
265 # If $var_to_set is missing or NULL, the value of $var_to_get is printed to
266 # standard output for capturing in a sub-shell (which is less-recommended
267 # because of performance degredation; for example, when called in a loop).
271 local __var_to_get="$1" __var_to_set="$2"
272 [ "$__var_to_set" ] || local value
273 eval ${__var_to_set:-value}=\"\${$__var_to_get}\"
274 eval [ \"\${$__var_to_get+set}\" ]
276 eval f_dprintf '"f_getvar: var=[%s] value=[%s] r=%u"' \
277 \"\$__var_to_get\" \"\$${__var_to_set:-value}\" \$__retval
278 [ "$__var_to_set" ] || { [ "$value" ] && echo "$value"; }
284 # Check if variable $var is set. Returns success if variable is set, otherwise
289 eval [ \"\${${1%%[$IFS]*}+set}\" ]
292 # f_die [$status [$format [$arguments ...]]]
294 # Abruptly terminate due to an error optionally displaying a message in a
295 # dialog box using printf(1) syntax.
299 local status=$FAILURE
301 # If there is at least one argument, take it as the status
302 if [ $# -gt 0 ]; then
307 # If there are still arguments left, pass them to f_show_msg
308 [ $# -gt 0 ] && f_show_msg "$@"
310 # Optionally call f_clean_up() function if it exists
311 f_have f_clean_up && f_clean_up
322 exec 2>&1 # fix sh(1) bug where stderr gets lost within async-trap
326 # f_show_info $format [$arguments ...]
328 # Display a message in a dialog infobox using printf(1) syntax.
336 # Use f_dialog_infobox from dialog.subr if possible, otherwise fall
337 # back to dialog(1) (without options, making it obvious when using
338 # un-aided system dialog).
340 if f_have f_dialog_info; then
343 dialog --infobox "$msg" 0 0
347 # f_show_msg $format [$arguments ...]
349 # Display a message in a dialog box using printf(1) syntax.
357 # Use f_dialog_msgbox from dialog.subr if possible, otherwise fall
358 # back to dialog(1) (without options, making it obvious when using
359 # un-aided system dialog).
361 if f_have f_dialog_msgbox; then
362 f_dialog_msgbox "$msg"
364 dialog --msgbox "$msg" 0 0
368 # f_show_err $format [$arguments ...]
370 # Display a message in a dialog box with ``Error'' i18n title (overridden by
371 # setting msg_error) using printf(1) syntax. If running non-interactively,
372 # the process will terminate (using [above] f_die()).
376 [ "$nonInteractive" ] && f_die
381 : ${msg:=${msg_an_unknown_error_occurred:-An unknown error occurred}}
383 if [ "$_DIALOG_SUBR" ]; then
384 f_dialog_title "${msg_error:-Error}"
385 f_dialog_msgbox "$msg"
386 f_dialog_title_restore
388 dialog --title "${msg_error:-Error}" --msgbox "$msg" 0 0
393 # f_yesno $format [$arguments ...]
395 # Display a message in a dialog yes/no box using printf(1) syntax.
403 # Use f_dialog_yesno from dialog.subr if possible, otherwise fall
404 # back to dialog(1) (without options, making it obvious when using
405 # un-aided system dialog).
407 if f_have f_dialog_yesno; then
408 f_dialog_yesno "$msg"
410 dialog --yesno "$msg" 0 0
414 # f_noyes $format [$arguments ...]
416 # Display a message in a dialog yes/no box using printf(1) syntax.
417 # NOTE: THis is just like the f_yesno function except "No" is default.
425 # Use f_dialog_noyes from dialog.subr if possible, otherwise fall
426 # back to dialog(1) (without options, making it obvious when using
427 # un-aided system dialog).
429 if f_have f_dialog_noyes; then
430 f_dialog_noyes "$msg"
432 dialog --defaultno --yesno "$msg" 0 0
438 # Display a language help-file. Automatically takes $LANG and $LC_ALL into
439 # consideration when displaying $file (suffix ".$LC_ALL" or ".$LANG" will
440 # automatically be added prior to loading the language help-file).
442 # If a language has been requested by setting either $LANG or $LC_ALL in the
443 # environment and the language-specific help-file does not exist we will fall
444 # back to $file without-suffix.
446 # If the language help-file does not exist, an error is displayed instead.
451 local lang="${LANG:-$LC_ALL}"
453 [ -f "$file.$lang" ] && file="$file.$lang"
456 # Use f_dialog_textbox from dialog.subr if possible, otherwise fall
457 # back to dialog(1) (without options, making it obvious when using
458 # un-aided system dialog).
460 if f_have f_dialog_textbox; then
461 f_dialog_textbox "$file"
463 dialog --msgbox "$( cat "$file" 2>&1 )" 0 0
469 # Include a shell subroutine file.
471 # If the subroutine file exists but returns error status during loading, exit
472 # is called and execution is prematurely terminated with the same error status.
477 f_dprintf "f_include: file=[%s]" "$file"
481 # f_include_lang $file
483 # Include a language file. Automatically takes $LANG and $LC_ALL into
484 # consideration when including $file (suffix ".$LC_ALL" or ".$LANG" will
485 # automatically by added prior to loading the language file).
487 # No error is produced if (a) a language has been requested (by setting either
488 # $LANG or $LC_ALL in the environment) and (b) the language file does not
489 # exist -- in which case we will fall back to loading $file without-suffix.
491 # If the language file exists but returns error status during loading, exit
492 # is called and execution is prematurely terminated with the same error status.
497 local lang="${LANG:-$LC_ALL}"
499 f_dprintf "f_include_lang: file=[%s] lang=[%s]" "$file" "$lang"
500 if [ -f "$file.$lang" ]; then
501 . "$file.$lang" || exit $?
507 # f_usage $file [$key1 $value1 ...]
509 # Display USAGE file with optional pre-processor macro definitions. The first
510 # argument is the template file containing the usage text to be displayed. If
511 # $LANG or $LC_ALL (in order of preference, respectively) is set, ".encoding"
512 # will automatically be appended as a suffix to the provided $file pathname.
514 # When processing $file, output begins at the first line containing that is
515 # (a) not a comment, (b) not empty, and (c) is not pure-whitespace. All lines
516 # appearing after this first-line are output, including (a) comments (b) empty
517 # lines, and (c) lines that are purely whitespace-only.
519 # If additional arguments appear after $file, substitutions are made while
520 # printing the contents of the USAGE file. The pre-processor macro syntax is in
521 # the style of autoconf(1), for example:
523 # f_usage $file "FOO" "BAR"
525 # Will cause instances of "@FOO@" appearing in $file to be replaced with the
526 # text "BAR" before bering printed to the screen.
528 # This function is a two-parter. Below is the awk(1) portion of the function,
529 # afterward is the sh(1) function which utilizes the below awk script.
534 if ( !found && $0 ~ /^[[:space:]]*($|#)/ ) next
542 local lang="${LANG:-$LC_ALL}"
544 f_dprintf "f_usage: file=[%s] lang=[%s]" "$file" "$lang"
549 if [ -f "$file.$lang" ]; then
550 usage=$( awk "$f_usage_awk" "$file.$lang" ) || exit $FAILURE
552 usage=$( awk "$f_usage_awk" "$file" ) || exit $FAILURE
555 while [ $# -gt 0 ]; do
558 usage=$( echo "$usage" | awk \
559 "{ gsub(/@$key@/, ENVIRON[\"value\"]); print }" )
563 f_err "%s\n" "$usage"
568 # f_index_file $keyword [$var_to_set]
570 # Process all INDEX files known to bsdconfig and return the path to first file
571 # containing a menu_selection line with a keyword portion matching $keyword.
573 # If $LANG or $LC_ALL (in order of preference, respectively) is set,
574 # "INDEX.encoding" files will be searched first.
576 # If no file is found, error status is returned along with the NULL string.
578 # If $var_to_set is NULL or missing, output is printed to stdout (which is less
579 # recommended due to performance degradation; in a loop for example).
581 # This function is a two-parter. Below is the awk(1) portion of the function,
582 # afterward is the sh(1) function which utilizes the below awk script.
585 # Variables that should be defined on the invocation line:
586 # -v keyword="keyword"
588 ( $0 ~ "^menu_selection=\"" keyword "\\|" ) {
597 local __keyword="$1" __var_to_set="$2"
598 local __lang="${LANG:-$LC_ALL}"
599 local __indexes="$BSDCFG_LIBE${BSDCFG_LIBE:+/}*/INDEX"
601 f_dprintf "f_index_file: keyword=[%s] lang=[%s]" "$__keyword" "$__lang"
603 if [ "$__lang" ]; then
604 if [ "$__var_to_set" ]; then
605 eval "$__var_to_set"='"$( awk -v keyword="$__keyword" \
606 "$f_index_file_awk" $__indexes.$__lang
607 )"' && return $SUCCESS
609 awk -v keyword="$__keyword" "$f_index_file_awk" \
610 $__indexes.$__lang && return $SUCCESS
612 # No match, fall-thru to non-i18n sources
614 if [ "$__var_to_set" ]; then
615 eval "$__var_to_set"='"$( awk -v keyword="$__keyword" \
616 "$f_index_file_awk" $__indexes )"' && return $SUCCESS
618 awk -v keyword="$__keyword" "$f_index_file_awk" $__indexes &&
622 # No match? Fall-thru to `local' libexec sources (add-on modules)
624 [ "$BSDCFG_LOCAL_LIBE" ] || return $FAILURE
625 __indexes="$BSDCFG_LOCAL_LIBE/*/INDEX"
626 if [ "$__lang" ]; then
627 if [ "$__var_to_set" ]; then
628 eval "$__var_to_set"='"$( awk -v keyword="$__keyword" \
629 "$f_index_file_awk" $__indexes.$__lang
630 )"' && return $SUCCESS
632 awk -v keyword="$__keyword" "$f_index_file_awk" \
633 $__indexes.$__lang && return $SUCCESS
635 # No match, fall-thru to non-i18n sources
637 if [ "$__var_to_set" ]; then
638 eval "$__var_to_set"='$( awk -v keyword="$__keyword" \
639 "$f_index_file_awk" $__indexes )"'
641 awk -v keyword="$__keyword" "$f_index_file_awk" $__indexes
645 # f_index_menusel_keyword $indexfile $pgm [$var_to_set]
647 # Process $indexfile and return only the keyword portion of the menu_selection
648 # line with a command portion matching $pgm.
650 # This function is for internationalization (i18n) mapping of the on-disk
651 # scriptname ($pgm) into the localized language (given language-specific
652 # $indexfile). If $LANG or $LC_ALL (in orderder of preference, respectively) is
653 # set, ".encoding" will automatically be appended as a suffix to the provided
654 # $indexfile pathname.
656 # If, within $indexfile, multiple $menu_selection values map to $pgm, only the
657 # first one will be returned. If no mapping can be made, the NULL string is
660 # If $indexfile does not exist, error status is returned with NULL.
662 # If $var_to_set is NULL or missing, output is printed to stdout (which is less
663 # recommended due to performance degradation; in a loop for example).
665 # This function is a two-parter. Below is the awk(1) portion of the function,
666 # afterward is the sh(1) function which utilizes the below awk script.
668 f_index_menusel_keyword_awk='
669 # Variables that should be defined on the invocation line:
670 # -v pgm="program_name"
673 prefix = "menu_selection=\""
674 plen = length(prefix)
678 if (!match($0, "^" prefix ".*\\|.*\"")) next
680 keyword = command = substr($0, plen + 1, RLENGTH - plen - 1)
681 sub(/^.*\|/, "", command)
682 sub(/\|.*$/, "", keyword)
684 if ( command == pgm )
693 f_index_menusel_keyword()
695 local __indexfile="$1" __pgm="$2" __var_to_set="$3"
696 local __lang="${LANG:-$LC_ALL}" __file="$__indexfile"
698 [ -f "$__indexfile.$__lang" ] && __file="$__indexfile.$__lang"
699 f_dprintf "f_index_menusel_keyword: index=[%s] pgm=[%s] lang=[%s]" \
700 "$__file" "$__pgm" "$__lang"
702 if [ "$__var_to_set" ]; then
703 setvar "$__var_to_set" "$( awk \
704 -v pgm="$__pgm" "$f_index_menusel_keyword_awk" "$__file"
707 awk -v pgm="$__pgm" "$f_index_menusel_keyword_awk" "$__file"
711 # f_index_menusel_command $indexfile $keyword [$var_to_set]
713 # Process $indexfile and return only the command portion of the menu_selection
714 # line with a keyword portion matching $keyword.
716 # This function is for mapping [possibly international] keywords into the
717 # command to be executed. If $LANG or $LC_ALL (order of preference) is set,
718 # ".encoding" will automatically be appended as a suffix to the provided
719 # $indexfile pathname.
721 # If, within $indexfile, multiple $menu_selection values map to $keyword, only
722 # the first one will be returned. If no mapping can be made, the NULL string is
725 # If $indexfile doesn't exist, error status is returned with NULL.
727 # If $var_to_set is NULL or missing, output is printed to stdout (which is less
728 # recommended due to performance degradation; in a loop for example).
730 # This function is a two-parter. Below is the awk(1) portion of the function,
731 # afterward is the sh(1) function which utilizes the below awk script.
733 f_index_menusel_command_awk='
734 # Variables that should be defined on the invocation line:
738 prefix = "menu_selection=\""
739 plen = length(prefix)
743 if (!match($0, "^" prefix ".*\\|.*\"")) next
745 keyword = command = substr($0, plen + 1, RLENGTH - plen - 1)
746 sub(/^.*\|/, "", command)
747 sub(/\|.*$/, "", keyword)
749 if ( keyword == key )
758 f_index_menusel_command()
760 local __indexfile="$1" __keyword="$2" __var_to_set="$3" __command
761 local __lang="${LANG:-$LC_ALL}" __file="$__indexfile"
763 [ -f "$__indexfile.$__lang" ] && __file="$__indexfile.$__lang"
764 f_dprintf "f_index_menusel_command: index=[%s] key=[%s] lang=[%s]" \
765 "$__file" "$__keyword" "$__lang"
767 [ -f "$__file" ] || return $FAILURE
768 __command=$( awk -v key="$__keyword" \
769 "$f_index_menusel_command_awk" "$__file" ) || return $FAILURE
772 # If the command pathname is not fully qualified fix-up/force to be
773 # relative to the $indexfile directory.
776 /*) : already fully qualified ;;
778 local __indexdir="${__indexfile%/*}"
779 [ "$__indexdir" != "$__indexfile" ] || __indexdir="."
780 __command="$__indexdir/$__command"
783 if [ "$__var_to_set" ]; then
784 setvar "$__var_to_set" "$__command"
792 # Returns true if running as init(1).
797 # When a custom init(8) performs an exec(3) to invoke a shell script,
798 # PID 1 becomes sh(1) and $PPID is set to 1 in the executed script.
800 [ ${PPID:-0} -eq 1 ] # Return status
803 # f_mounted $local_directory
805 # Return success if a filesystem is mounted on a particular directory.
810 [ -d "$dir" ] || return $FAILURE
811 mount | grep -Eq " on $dir \([^)]+\)$"
814 # f_eval_catch [-de] [-k $var_to_set] $funcname $utility \
815 # $format [$arguments ...]
817 # Silently evaluate a command in a sub-shell and test for error. If debugging
818 # is enabled a copy of the command and its output is sent to debug (either
819 # stdout or file depending on environment). If an error occurs, output of the
820 # command is displayed in a dialog(1) msgbox using the [above] f_show_err()
821 # function (unless optional `-d' flag is given, then no dialog).
823 # The $funcname argument is sent to debugging while the $utility argument is
824 # used in the title of the dialog box. The command that is executed as well as
825 # sent to debugging with $funcname is the product of the printf(1) syntax
826 # produced by $format with optional $arguments.
828 # The following options are supported:
830 # -d Do not use dialog(1).
831 # -e Produce error text from failed command on stderr.
832 # -k var Save output from the command in var.
837 # f_eval_catch myfunc echo 'echo "%s"' "Hello, World!"
839 # Produces the following debug output:
841 # DEBUG: myfunc: echo "Hello, World!"
842 # DEBUG: myfunc: retval=0 <output below>
848 # f_eval_catch -k contents myfunc cat 'cat "%s"' /some/file
849 # # dialog(1) Error ``cat: /some/file: No such file or directory''
850 # # contents=[cat: /some/file: No such file or directory]
852 # Produces the following debug output:
854 # DEBUG: myfunc: cat "/some/file"
855 # DEBUG: myfunc: retval=1 <output below>
856 # cat: /some/file: No such file or directory
861 # echo 123 | f_eval_catch myfunc rev rev
863 # Produces the following debug output:
866 # DEBUG: myfunc: retval=0 <output below>
872 # f_eval_catch myfunc true true
874 # Produces the following debug output:
876 # DEBUG: myfunc: true
877 # DEBUG: myfunc: retval=0 <no output>
881 # f_eval_catch -de myfunc ls 'ls "%s"' /some/dir
882 # # Output on stderr ``ls: /some/dir: No such file or directory''
886 # f_eval_catch -dek contents myfunc ls 'ls "%s"' /etc
887 # # Output from `ls' sent to stderr and also saved in $contents
891 local __no_dialog= __show_err= __var_to_set=
894 # Process local function arguments
897 while getopts "dek:" __flag > /dev/null; do
901 k) __var_to_set="$OPTARG" ;;
904 shift $(( $OPTIND - 1 ))
906 local __funcname="$1" __utility="$2"; shift 2
907 local __cmd __output __retval
909 __cmd=$( printf -- "$@" )
910 f_dprintf "%s: %s" "$__funcname" "$__cmd" # Log command *before* eval
911 __output=$( exec 2>&1; eval "$__cmd" )
913 if [ "$__output" ]; then
914 [ "$__show_err" ] && echo "$__output" >&2
915 f_dprintf "%s: retval=%i <output below>\n%s" "$__funcname" \
916 $__retval "$__output"
918 f_dprintf "%s: retval=%i <no output>" "$__funcname" $__retval
921 ! [ "$__no_dialog" -o "$nonInteractive" -o $__retval -eq $SUCCESS ] &&
922 msg_error="${msg_error:-Error}${__utility:+: $__utility}" \
923 f_show_err "%s" "$__output"
924 # NB: f_show_err will handle NULL output appropriately
926 [ "$__var_to_set" ] && setvar "$__var_to_set" "$__output"
931 # f_count $var_to_set arguments ...
933 # Sets $var_to_set to the number of arguments minus one (the effective number
934 # of arguments following $var_to_set).
937 # f_count count dog house # count=[2]
941 setvar "$1" $(( $# - 1 ))
944 # f_count_ifs $var_to_set string ...
946 # Sets $var_to_set to the number of words (split by the internal field
947 # separator, IFS) following $var_to_set.
951 # string="word1 word2 word3"
952 # f_count_ifs count "$string" # count=[3]
953 # f_count_ifs count $string # count=[3]
957 # IFS=. f_count_ifs count www.freebsd.org # count=[3]
959 # NB: Make sure to use double-quotes if you are using a custom value for IFS
960 # and you don't want the current value to effect the result. See example 3.
965 # IFS=- f_count_ifs count "$string" # count=[3]
966 # IFS=- f_count_ifs count $string # count=[4]
970 local __var_to_set="$1"
973 setvar "$__var_to_set" $#
976 ############################################################ MAIN
979 # Trap signals so we can recover gracefully
981 trap 'f_interrupt' SIGINT
982 trap 'f_die' SIGTERM SIGPIPE SIGXCPU SIGXFSZ \
983 SIGFPE SIGTRAP SIGABRT SIGSEGV
984 trap '' SIGALRM SIGPROF SIGUSR1 SIGUSR2 SIGHUP SIGVTALRM
987 # Clone terminal stdout/stderr so we can redirect to it from within sub-shells
989 eval exec $TERMINAL_STDOUT_PASSTHRU\>\&1
990 eval exec $TERMINAL_STDERR_PASSTHRU\>\&2
993 # Self-initialize unless requested otherwise
995 f_dprintf "%s: DEBUG_SELF_INITIALIZE=[%s]" \
996 dialog.subr "$DEBUG_SELF_INITIALIZE"
997 case "$DEBUG_SELF_INITIALIZE" in
998 ""|0|[Nn][Oo]|[Oo][Ff][Ff]|[Ff][Aa][Ll][Ss][Ee]) : do nothing ;;
1003 # Log our operating environment for debugging purposes
1005 f_dprintf "UNAME_S=[%s] UNAME_P=[%s] UNAME_R=[%s]" \
1006 "$UNAME_S" "$UNAME_P" "$UNAME_R"
1008 f_dprintf "%s: Successfully loaded." common.subr
1010 fi # ! $_COMMON_SUBR