3 # This defines some general, useful functions.
5 # test whether we've been here before or not.
7 type function_sentinel &>/dev/null
9 # there was no error, so we can skip the inits.
10 if [ ! -z "$SHELL_DEBUG" ]; then
11 echo "skipping function definitions, because already defined."
18 if [ -z "$skip_all" ]; then
20 if [ ! -z "$SHELL_DEBUG" ]; then
21 echo "feisty meow function definitions beginning now..."
24 # a handy little method that can be used for date strings. it was getting
25 # really tiresome how many different ways the script did the date formatting.
26 function date_stringer() {
28 if [ -z "$sep" ]; then sep='_'; fi
29 date +"%Y$sep%m$sep%d$sep%H%M$sep%S" | tr -d '/\n/'
32 # makes a directory of the name specified and then tries to change the
33 # current directory to that directory.
35 if [ ! -d "$1" ]; then mkdir -p "$1"; fi
40 [[ "$(declare -p $1)" =~ "declare -a" ]]
48 # displays the value of a variable in bash friendly format.
53 local varname="$1"; shift
54 if [ -z "$varname" ]; then
58 if is_alias "$varname"; then
59 #echo found $varname is alias
60 local tmpfile="$(mktemp $TMP/aliasout.XXXXXX)"
61 alias $varname | sed -e 's/.*=//' >$tmpfile
62 echo "alias $varname=$(cat $tmpfile)"
64 elif [ -z "${!varname}" ]; then
65 echo "$varname undefined"
67 if is_array "$varname"; then
68 #echo found $varname is array var
70 eval temparray="(\${$varname[@]})"
71 echo "$varname=(${temparray[@]})"
72 #hmmm: would be nice to print above with elements enclosed in quotes, so that we can properly
73 # see ones that have spaces in them.
75 #echo found $varname is simple
76 echo "$varname=${!varname}"
83 # when passed a list of things, this will return the unique items from that list as an echo.
86 # change the eol character so things are easier.
89 # do the uniquification.
91 # return the former eol characters to their place.
95 # sets the variable in parameter 1 to the value in parameter 2, but only if
96 # that variable was undefined.
97 function set_var_if_undefined()
99 local var_name="$1"; shift
100 local var_value="$1"; shift
101 if [ -z "${!var_name}" ]; then
102 eval export $var_name="$var_value"
106 function success_sound()
108 if [ ! -z "$CLAM_FINISH_SOUND" ]; then
109 bash $FEISTY_MEOW_SCRIPTS/multimedia/sound_play.sh "$CLAM_FINISH_SOUND"
113 function error_sound()
115 if [ ! -z "$CLAM_ERROR_SOUND" ]; then
116 bash $FEISTY_MEOW_SCRIPTS/multimedia/sound_play.sh "$CLAM_ERROR_SOUND"
120 # checks the result of the last command that was run, and if that failed,
121 # then this complains and exits from bash. the function parameters are
122 # used as the message to print as a complaint.
123 function check_result()
125 if [ $? -ne 0 ]; then
126 echo -e "failed on: $*"
132 # locates a process given a search pattern to match in the process list.
133 # supports a single command line flag style parameter of "-u USERNAME";
134 # if the -u flag is found, a username is expected afterwards, and only the
135 # processes of that user are considered.
137 local -a patterns=("${@}")
139 #echo patterns list is: "${patterns[@]}"
143 if [ "${patterns[0]}" == "-u" ]; then
144 user_flag="-u ${patterns[1]}"
145 #echo "found a -u parm and user=${patterns[1]}"
146 # void the two elements with that user flag so we don't use them as patterns.
147 unset patterns[0] patterns[1]=
153 local PID_DUMP="$(mktemp "$TMP/zz_pidlist.XXXXXX")"
156 if [ "$OS" == "Windows_NT" ]; then
157 # gets cygwin's (god awful) ps to show windoze processes also.
158 local EXTRA_DOZER_FLAGS="-W"
159 # pattern to use for peeling off the process numbers.
160 local pid_finder_pattern='s/ *\([0-9][0-9]*\) *.*$/\1/p'
163 # flags which clean up the process listing output on unixes.
164 # apparently cygwin doesn't count as a type of unix, because their
165 # crummy specialized ps command doesn't support normal ps flags.
166 local EXTRA_UNIX_FLAGS="-o pid,args"
167 # pattern to use for peeling off the process numbers.
168 local pid_finder_pattern='s/^[[:space:]]*\([0-9][0-9]*\).*$/\1/p'
171 /bin/ps $EXTRA_DOZER_FLAGS $EXTRA_UNIX_FLAGS $user_flag | tail -n +2 >$PID_DUMP
173 #echo got all this stuff in the pid dump file:
177 # search for the pattern the user wants to find, and just pluck the process
178 # ids out of the results.
180 for i in "${patterns[@]}"; do
181 PIDS_SOUGHT+=($(cat $PID_DUMP \
183 | sed -n -e "$pid_finder_pattern"))
186 #echo pids sought list became:
187 #echo "${PIDS_SOUGHT[@]}"
190 if [ ${#PIDS_SOUGHT[*]} -ne 0 ]; then
191 local PIDS_SOUGHT2=$(printf -- '%s\n' ${PIDS_SOUGHT[@]} | sort | uniq)
193 PIDS_SOUGHT=${PIDS_SOUGHT2[*]}
194 echo ${PIDS_SOUGHT[*]}
199 # finds all processes matching the pattern specified and shows their full
200 # process listing (whereas psfind just lists process ids).
203 echo "psa finds processes by pattern, but there was no pattern on the command line."
206 local -a patterns=("${@}")
207 p=$(psfind "${patterns[@]}")
213 if [ "${patterns[0]}" == "-u" ]; then
214 # void the two elements with that user flag so we don't use them as patterns.
215 unset patterns[0] patterns[1]=
219 echo "Processes matching ${patterns[@]}..."
221 if [ -n "$IS_DARWIN" ]; then
224 # only print the header the first time.
225 if [ -z "$fuzil_sentinel" ]; then
228 ps $i -w -u | sed -e '1d'
233 # cases besides mac os x's darwin.
234 if [ "$OS" == "Windows_NT" ]; then
235 # special case for windows.
238 ps -W -p $curr | tail -n +2
241 # normal OSes can handle a nice simple query.
247 # an unfortunately similarly named function to the above 'ps' as in process
248 # methods, but this 'ps' stands for postscript. this takes a postscript file
249 # and converts it into pcl3 printer language and then ships it to the printer.
250 # this mostly makes sense for an environment where one's default printer is
251 # pcl. if the input postscript causes ghostscript to bomb out, there has been
252 # some good success running ps2ps on the input file and using the cleaned
253 # postscript file for printing.
254 function ps2pcl2lpr() {
256 gs -sDEVICE=pcl3 -sOutputFile=- -sPAPERSIZE=letter "$i" | lpr -l
260 # function fix_alsa() {
261 # sudo /etc/init.d/alsasound restart
266 #hmmm: ugly absolute path here.
268 restore_terminal_title
271 # switches from a /X/path form to an X:/ form. this also processes cygwin paths.
272 function unix_to_dos_path() {
273 # we usually remove dos slashes in favor of forward slashes.
275 if [[ ! "$OS" =~ ^[Ww][iI][nN] ]]; then
276 # fake this value for non-windows (non-cygwin) platforms.
279 # for cygwin, we must replace the /home/X path with an absolute one, since cygwin
280 # insists on the /home form instead of /c/cygwin/home being possible. this is
281 # super frustrating and nightmarish.
282 DOSSYHOME="$(cygpath -am "$HOME")"
285 if [ ! -z "$SERIOUS_SLASH_TREATMENT" ]; then
286 # unless this flag is set, in which case we force dos slashes.
287 echo "$1" | sed -e "s?^$HOME?$DOSSYHOME?g" | sed -e 's/\\/\//g' | sed -e 's/\/cygdrive//' | sed -e 's/\/\([a-zA-Z]\)\/\(.*\)/\1:\/\2/' | sed -e 's/\//\\/g'
289 echo "$1" | sed -e "s?^$HOME?$DOSSYHOME?g" | sed -e 's/\\/\//g' | sed -e 's/\/cygdrive//' | sed -e 's/\/\([a-zA-Z]\)\/\(.*\)/\1:\/\2/'
293 # switches from an X:/ form to a /cygdrive/X/path form. this is only useful
294 # for the cygwin environment currently.
295 function dos_to_unix_path() {
296 # we always remove dos slashes in favor of forward slashes.
297 #old: echo "$1" | sed -e 's/\\/\//g' | sed -e 's/\([a-zA-Z]\):\/\(.*\)/\/\1\/\2/'
298 echo "$1" | sed -e 's/\\/\//g' | sed -e 's/\([a-zA-Z]\):\/\(.*\)/\/cygdrive\/\1\/\2/'
301 # returns a successful value (0) if this system is debian or ubuntu.
302 function debian_like() {
303 # decide if we think this is debian or ubuntu or a variant.
304 DEBIAN_LIKE=$(if [ ! -z "$(grep -i debian /etc/issue)" \
305 -o ! -z "$(grep -i ubuntu /etc/issue)" ]; then echo 1; else echo 0; fi)
306 if [ $DEBIAN_LIKE -eq 1 ]; then
307 # success; this is debianish.
310 # this seems like some other OS.
315 # su function: makes su perform a login.
316 # for some OSes, this transfers the X authority information to the new login.
319 # debian currently requires the full version which imports X authority
320 # information for su.
322 # get the x authority info for our current user.
323 source "$FEISTY_MEOW_SCRIPTS/security/get_x_auth.sh"
325 if [ -z "$X_auth_info" ]; then
326 # if there's no authentication info to pass along, we just do a normal su.
329 # under X, we update the new login's authority info with the previous
331 (unset XAUTHORITY; /bin/su -l $* -c "$X_auth_info ; export DISPLAY=$DISPLAY ; bash")
334 # non-debian supposedly doesn't need the extra overhead any more.
335 # or at least suse doesn't, which is the other one we've tested on.
340 # sudo function wraps the normal sudo by ensuring we replace the terminal
341 # label if they're doing an su with the sudo.
343 # local first_command="$1"
346 restore_terminal_title
347 # if [ "$first_command" == "su" ]; then
348 # # yep, they were doing an su, but they're back now.
349 # label_terminal_with_info
353 # trashes the .#blah files that cvs and svn leave behind when finding conflicts.
354 # this kind of assumes you've already checked them for any salient facts.
355 function clean_cvs_junk() {
357 find $i -follow -type f -iname ".#*" -exec perl $FEISTY_MEOW_SCRIPTS/files/safedel.pl {} ";"
361 # overlay for nechung binary so that we can complain less grossly about it when it's missing.
363 local wheres_nechung=$(which nechung 2>/dev/null)
364 if [ -z "$wheres_nechung" ]; then
365 echo "The nechung oracle program cannot be found. You may want to consider"
366 echo "rebuilding the feisty meow applications with this command:"
367 echo "bash $FEISTY_MEOW_SCRIPTS/generator/produce_feisty_meow.sh"
373 # recreates all the generated files that the feisty meow scripts use.
374 function regenerate() {
375 # do the bootstrapping process again.
377 echo "regenerating feisty meow script environment."
378 bash $FEISTY_MEOW_SCRIPTS/core/reconfigure_feisty_meow.sh
380 # force a full reload by turning off sentinel variables and methods.
381 unset -v CORE_VARIABLES_LOADED FEISTY_MEOW_LOADING_DOCK USER_CUSTOMIZATIONS_LOADED
382 unalias CORE_ALIASES_LOADED &>/dev/null
383 unset -f function_sentinel
384 # reload feisty meow environment in current shell.
385 source "$FEISTY_MEOW_SCRIPTS/core/launch_feisty_meow.sh"
386 # run nechung oracle to give user a new fortune.
388 restore_terminal_title
391 # copies a set of custom scripts into the proper location for feisty meow
392 # to merge their functions and aliases with the standard set.
393 function recustomize()
395 local custom_user="$1"; shift
396 if [ -z "$custom_user" ]; then
397 # use our default example user if there was no name provided.
403 if [ ! -d "$FEISTY_MEOW_SCRIPTS/customize/$custom_user" ]; then
404 echo "The customization folder provided for $custom_user should be:"
405 echo " '$FEISTY_MEOW_SCRIPTS/customize/$custom_user'"
406 echo "but that folder does not exist. Skipping customization."
409 regenerate >/dev/null
410 pushd "$FEISTY_MEOW_LOADING_DOCK/custom" &>/dev/null
411 incongruous_files="$(bash "$FEISTY_MEOW_SCRIPTS/files/list_non_dupes.sh" "$FEISTY_MEOW_SCRIPTS/customize/$custom_user" "$FEISTY_MEOW_LOADING_DOCK/custom")"
413 #echo "the incongruous files list is: $incongruous_files"
414 # disallow a single character result, since we get "*" as result when nothing exists yet.
415 if [ ${#incongruous_files} -ge 2 ]; then
416 echo "cleaning unknown older overrides..."
417 perl "$FEISTY_MEOW_SCRIPTS/files/safedel.pl" $incongruous_files
421 echo "copying custom overrides for $custom_user"
422 mkdir -p "$FEISTY_MEOW_LOADING_DOCK/custom" 2>/dev/null
423 perl "$FEISTY_MEOW_SCRIPTS/text/cpdiff.pl" "$FEISTY_MEOW_SCRIPTS/customize/$custom_user" "$FEISTY_MEOW_LOADING_DOCK/custom"
424 if [ -d "$FEISTY_MEOW_SCRIPTS/customize/$custom_user/scripts" ]; then
425 echo "copying custom scripts for $custom_user"
426 \cp -R "$FEISTY_MEOW_SCRIPTS/customize/$custom_user/scripts" "$FEISTY_MEOW_LOADING_DOCK/custom/"
431 restore_terminal_title
434 # generates a random password where the first parameter is the number of characters
435 # in the password (default 20) and the second parameter specifies whether to use
436 # special characters (1) or not (0).
437 # found function at http://legroom.net/2010/05/06/bash-random-password-generator
438 function random_password()
440 [ "$2" == "0" ] && CHAR="[:alnum:]" || CHAR="[:graph:]"
441 cat /dev/urandom | tr -cd "$CHAR" | head -c ${1:-32}
445 # a wrapper for the which command that finds items on the path. some OSes
446 # do not provide which, so we want to not be spewing errors when that
451 which which &>/dev/null
452 if [ $? -ne 0 ]; then
453 # there is no which command here. we produce nothing due to this.
456 echo $(which $to_find)
459 #hmmm: improve this by not adding the link
460 # if already there, or if the drive is not valid.
461 function add_cygwin_drive_mounts() {
462 for i in c d e f g h q z ; do
463 ln -s /cygdrive/$i $i
467 ############################
469 # takes a file to modify, and then it will replace any occurrences of the
470 # pattern provided as the second parameter with the text in the third
472 function replace_pattern_in_file()
474 local file="$1"; shift
475 local pattern="$1"; shift
476 local replacement="$1"; shift
477 if [ -z "$file" -o -z "$pattern" -o -z "$replacement" ]; then
478 echo "replace_pattern_in_file: needs a filename, a pattern to replace, and the"
479 echo "text to replace that pattern with."
482 sed -i -e "s%$pattern%$replacement%g" "$file"
485 # similar to replace_pattern_in_file, but also will add the new value
486 # when the old one did not already exist in the file.
487 function replace_if_exists_or_add()
489 local file="$1"; shift
490 local phrase="$1"; shift
491 local replacement="$1"; shift
492 if [ -z "$file" -o ! -f "$file" -o -z "$phrase" -o -z "$replacement" ]; then
493 echo "replace_if_exists_or_add: needs a filename, a phrase to replace, and the"
494 echo "text to replace that phrase with."
497 grep "$phrase" "$file" >/dev/null
498 # replace if the phrase is there, otherwise add it.
499 if [ $? -eq 0 ]; then
500 replace_pattern_in_file "$file" "$phrase" "$replacement"
502 # this had better be the complete line.
503 echo "$replacement" >>"$file"
507 ############################
509 # finds a variable (first parameter) in a particular property file
510 # (second parameter). the expected format for the file is:
512 function seek_variable()
514 local find_var="$1"; shift
515 local file="$1"; shift
516 if [ -z "$find_var" -o -z "$file" -o ! -f "$file" ]; then
517 echo -e "seek_variable: needs two parameters, firstly a variable name, and\nsecondly a file where the variable's value will be sought." 1>&2
522 if [ ${#line} -eq 0 ]; then continue; fi
523 # split the line into the variable name and value.
524 IFS='=' read -a assignment <<< "$line"
525 local var="${assignment[0]}"
526 local value="${assignment[1]}"
527 if [ "${value:0:1}" == '"' ]; then
528 # assume the entry was in quotes and remove them.
529 value="${value:1:$((${#value} - 2))}"
531 if [ "$find_var" == "$var" ]; then
537 # finds a variable (first parameter) in a particular XML format file
538 # (second parameter). the expected format for the file is:
539 # ... name="varX" value="valueX" ...
540 function seek_variable_in_xml()
542 local find_var="$1"; shift
543 local file="$1"; shift
544 if [ -z "$find_var" -o -z "$file" -o ! -f "$file" ]; then
545 echo "seek_variable_in_xml: needs two parameters, firstly a variable name, and"
546 echo "secondly an XML file where the variable's value will be sought."
551 if [ ${#line} -eq 0 ]; then continue; fi
552 # process the line to make it more conventional looking.
553 line="$(echo "$line" | sed -e 's/.*name="\([^"]*\)" value="\([^"]*\)"/\1=\2/')"
554 # split the line into the variable name and value.
555 IFS='=' read -a assignment <<< "$line"
556 local var="${assignment[0]}"
557 local value="${assignment[1]}"
558 if [ "${value:0:1}" == '"' ]; then
559 # assume the entry was in quotes and remove them.
560 value="${value:1:$((${#value} - 2))}"
562 if [ "$find_var" == "$var" ]; then
568 ############################
570 # goes to a particular directory passed as parameter 1, and then removes all
571 # the parameters after that from that directory.
572 function push_whack_pop()
574 local dir="$1"; shift
575 pushd "$dir" &>/dev/null
576 if [ $? -ne 0 ]; then echo failed to enter dir--quitting.; fi
577 rm -rf $* &>/dev/null
578 if [ $? -ne 0 ]; then echo received a failure code when removing.; fi
584 while [ $# -gt 0 ]; do
586 if [ ! -f "$arg" -a ! -d "$arg" ]; then
587 echo "failure to find a file or directory named '$arg'."
591 # first we will capture the output of the character replacement operation for reporting.
592 # this is done first since some filenames can't be properly renamed in perl (e.g. if they
593 # have pipe characters apparently).
594 intermediate_name="$(bash "$FEISTY_MEOW_SCRIPTS/files/replace_spaces_with_underscores.sh" "$arg")"
595 local saw_intermediate_result=0
596 if [ -z "$intermediate_name" ]; then
597 # make sure we report something, if there are no further name changes.
598 intermediate_name="'$arg'"
600 # now zap the first part of the name off (since original name isn't needed).
601 intermediate_name="$(echo $intermediate_name | sed -e 's/.*=> //')"
602 saw_intermediate_result=1
605 # first we rename the file to be lower case.
606 actual_file="$(echo $intermediate_name | sed -e "s/'\([^']*\)'/\1/")"
607 final_name="$(perl $FEISTY_MEOW_SCRIPTS/files/renlower.pl "$actual_file")"
608 local saw_final_result=0
609 if [ -z "$final_name" ]; then
610 final_name="$intermediate_name"
612 final_name="$(echo $final_name | sed -e 's/.*=> //')"
615 #echo intermed=$saw_intermediate_result
616 #echo final=$saw_final_result
618 if [[ $saw_intermediate_result != 0 || $saw_final_result != 0 ]]; then
619 # printout the combined operation results.
620 echo "'$arg' => $final_name"
627 # new breed of definer functions goes here. still in progress.
629 # defines an alias and remembers that this is a new or modified definition.
630 # if the feisty meow codebase is unloaded, then so are all the aliases that
632 function define_yeti_alias()
634 # if alias exists already, save old value for restore,
635 # otherwise save null value for restore,
636 # have to handle unaliasing if there was no prior value of one
638 # add alias name to a list of feisty defined aliases.
640 #hmmm: first implem, just do the alias and get that working...
647 # defines a variable within the feisty meow environment and remembers that
648 # this is a new or modified definition. if the feisty meow codebase is
649 # unloaded, then so are all the variables that were defined.
650 # this function always exports the variables it defines.
651 # function define_yeti_variable()
653 ## if variable exists already, save old value for restore,
654 ## otherwise save null value for restore,
655 ## have to handle unsetting if there was no prior value of one
657 ## add variable name to a list of feisty defined variables.
659 ##hmmm: first implem just sets it up and exports the variable.
660 ## i.e., this method always exports.
669 #hmmm: this points to an extended functions file being needed; not all of these are core.
671 # displays documentation in "md" formatted files.
674 local file="$1"; shift
675 pandoc "$file" | lynx -stdin
680 # just shows a separator line for an 80 column console, or uses the first
681 # parameter as the number of columns to expect.
685 if [ -z "$count" ]; then
690 for ((i=0; i < $count - 1; i++)); do
696 # alias for separator.
704 function function_sentinel()
709 if [ ! -z "$SHELL_DEBUG" ]; then echo "feisty meow function definitions done."; fi
713 # test code for set_var_if_undefined.
715 if [ $run_test != 0 ]; then
716 echo running tests on set_var_if_undefined.
718 set_var_if_undefined flagrant forknordle
719 check_result "testing if defined variable would be whacked"
720 if [ $flagrant != petunia ]; then
721 echo set_var_if_undefined failed to leave the test variable alone
724 unset bobblehead_stomper
725 set_var_if_undefined bobblehead_stomper endurance
726 if [ $bobblehead_stomper != endurance ]; then
727 echo set_var_if_undefined failed to set a variable that was not defined yet