3 # This defines some general, useful functions.
5 # test whether we've been here before or not.
7 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 # sets the variable in parameter 1 to the value in parameter 2, but only if
84 # that variable was undefined.
85 function set_var_if_undefined()
87 local var_name="$1"; shift
88 local var_value="$1"; shift
89 if [ -z "${!var_name}" ]; then
90 eval export $var_name="$var_value"
94 function success_sound()
96 if [ ! -z "$CLAM_FINISH_SOUND" ]; then
97 bash $FEISTY_MEOW_SCRIPTS/multimedia/sound_play.sh "$CLAM_FINISH_SOUND"
101 function error_sound()
103 if [ ! -z "$CLAM_ERROR_SOUND" ]; then
104 bash $FEISTY_MEOW_SCRIPTS/multimedia/sound_play.sh "$CLAM_ERROR_SOUND"
108 # checks the result of the last command that was run, and if that failed,
109 # then this complains and exits from bash. the function parameters are
110 # used as the message to print as a complaint.
111 function check_result()
113 if [ $? -ne 0 ]; then
114 echo -e "failed on: $*"
120 # locates a process given a search pattern to match in the process list.
121 # supports a single command line flag style parameter of "-u USERNAME";
122 # if the -u flag is found, a username is expected afterwards, and only the
123 # processes of that user are considered.
125 local -a patterns=("${@}")
127 #echo patterns list is: "${patterns[@]}"
131 if [ "${patterns[0]}" == "-u" ]; then
132 user_flag="-u ${patterns[1]}"
133 #echo "found a -u parm and user=${patterns[1]}"
134 # void the two elements with that user flag so we don't use them as patterns.
135 unset patterns[0] patterns[1]=
141 local PID_DUMP="$(mktemp "$TMP/zz_pidlist.XXXXXX")"
144 if [ "$OS" == "Windows_NT" ]; then
145 # gets cygwin's (god awful) ps to show windoze processes also.
146 local EXTRA_DOZER_FLAGS="-W"
147 # pattern to use for peeling off the process numbers.
148 local pid_finder_pattern='s/ *\([0-9][0-9]*\) *.*$/\1/p'
151 # flags which clean up the output on unixes, which apparently cygwin
152 # doesn't count as. their crappy specialized ps doesn't support this.
153 local EXTRA_UNIX_FLAGS="-o pid,args"
154 # pattern to use for peeling off the process numbers.
155 local pid_finder_pattern='s/^[[:space:]]*\([0-9][0-9]*\).*$/\1/p'
158 /bin/ps $EXTRA_DOZER_FLAGS $EXTRA_UNIX_FLAGS $user_flag | tail -n +2 >$PID_DUMP
160 #echo got all this stuff in the pid dump file:
164 # search for the pattern the user wants to find, and just pluck the process
165 # ids out of the results.
167 for i in "${patterns[@]}"; do
168 PIDS_SOUGHT+=($(cat $PID_DUMP \
170 | sed -n -e "$pid_finder_pattern"))
173 #echo pids sought list became:
174 #echo "${PIDS_SOUGHT[@]}"
177 if [ ${#PIDS_SOUGHT[*]} -ne 0 ]; then
178 local PIDS_SOUGHT2=$(printf -- '%s\n' ${PIDS_SOUGHT[@]} | sort | uniq)
180 PIDS_SOUGHT=${PIDS_SOUGHT2[*]}
181 echo ${PIDS_SOUGHT[*]}
186 # finds all processes matching the pattern specified and shows their full
187 # process listing (whereas psfind just lists process ids).
190 echo "psa finds processes by pattern, but there was no pattern on the command line."
193 local -a patterns=("${@}")
194 p=$(psfind "${patterns[@]}")
200 if [ "${patterns[0]}" == "-u" ]; then
201 # void the two elements with that user flag so we don't use them as patterns.
202 unset patterns[0] patterns[1]=
206 echo "Processes matching ${patterns[@]}..."
208 if [ -n "$IS_DARWIN" ]; then
211 # only print the header the first time.
212 if [ -z "$fuzil_sentinel" ]; then
215 ps $i -w -u | sed -e '1d'
220 # cases besides mac os x's darwin.
221 if [ "$OS" == "Windows_NT" ]; then
222 # special case for windows.
225 ps -W -p $curr | tail -n +2
228 # normal OSes can handle a nice simple query.
234 # an unfortunately similarly named function to the above 'ps' as in process
235 # methods, but this 'ps' stands for postscript. this takes a postscript file
236 # and converts it into pcl3 printer language and then ships it to the printer.
237 # this mostly makes sense for an environment where one's default printer is
238 # pcl. if the input postscript causes ghostscript to bomb out, there has been
239 # some good success running ps2ps on the input file and using the cleaned
240 # postscript file for printing.
241 function ps2pcl2lpr() {
243 gs -sDEVICE=pcl3 -sOutputFile=- -sPAPERSIZE=letter "$i" | lpr -l
247 function fix_alsa() {
248 sudo /etc/init.d/alsasound restart
251 # switches from a /X/path form to an X:/ form. this also processes cygwin paths.
252 function unix_to_dos_path() {
253 # we usually remove dos slashes in favor of forward slashes.
255 if [[ ! "$OS" =~ ^[Ww][iI][nN] ]]; then
256 # fake this value for non-windows (non-cygwin) platforms.
259 # for cygwin, we must replace the /home/X path with an absolute one, since cygwin
260 # insists on the /home form instead of /c/cygwin/home being possible. this is
261 # super frustrating and nightmarish.
262 DOSSYHOME="$(cygpath -am "$HOME")"
265 if [ ! -z "$SERIOUS_SLASH_TREATMENT" ]; then
266 # unless this flag is set, in which case we force dos slashes.
267 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'
269 echo "$1" | sed -e "s?^$HOME?$DOSSYHOME?g" | sed -e 's/\\/\//g' | sed -e 's/\/cygdrive//' | sed -e 's/\/\([a-zA-Z]\)\/\(.*\)/\1:\/\2/'
273 # switches from an X:/ form to a /cygdrive/X/path form. this is only useful
274 # for the cygwin environment currently.
275 function dos_to_unix_path() {
276 # we always remove dos slashes in favor of forward slashes.
277 #old: echo "$1" | sed -e 's/\\/\//g' | sed -e 's/\([a-zA-Z]\):\/\(.*\)/\/\1\/\2/'
278 echo "$1" | sed -e 's/\\/\//g' | sed -e 's/\([a-zA-Z]\):\/\(.*\)/\/cygdrive\/\1\/\2/'
281 # returns a successful value (0) if this system is debian or ubuntu.
282 function debian_like() {
283 # decide if we think this is debian or ubuntu or a variant.
284 DEBIAN_LIKE=$(if [ ! -z "$(grep -i debian /etc/issue)" \
285 -o ! -z "$(grep -i ubuntu /etc/issue)" ]; then echo 1; else echo 0; fi)
286 if [ $DEBIAN_LIKE -eq 1 ]; then
287 # success; this is debianish.
290 # this seems like some other OS.
295 # su function: makes su perform a login.
296 # for some OSes, this transfers the X authority information to the new login.
299 # debian currently requires the full version which imports X authority
300 # information for su.
302 # get the x authority info for our current user.
303 source $FEISTY_MEOW_SCRIPTS/x_win/get_x_auth.sh
305 if [ -z "$X_auth_info" ]; then
306 # if there's no authentication info to pass along, we just do a normal su.
309 # under X, we update the new login's authority info with the previous
311 (unset XAUTHORITY; /bin/su -l $* -c "$X_auth_info ; export DISPLAY=$DISPLAY ; bash")
314 # non-debian supposedly doesn't need the extra overhead any more.
315 # or at least suse doesn't, which is the other one we've tested on.
319 # relabel the console after returning.
320 bash $FEISTY_MEOW_SCRIPTS/tty/label_terminal_with_infos.sh
323 # sudo function wraps the normal sudo by ensuring we replace the terminal
324 # label if they're doing an su with the sudo.
326 local first_command="$1"
328 if [ "$first_command" == "su" ]; then
329 # yep, they were doing an su, but they're back now.
330 bash $FEISTY_MEOW_SCRIPTS/tty/label_terminal_with_infos.sh
334 # trashes the .#blah files that cvs and svn leave behind when finding conflicts.
335 # this kind of assumes you've already checked them for any salient facts.
336 function clean_cvs_junk() {
338 find $i -follow -type f -iname ".#*" -exec perl $FEISTY_MEOW_SCRIPTS/files/safedel.pl {} ";"
342 # overlay for nechung binary so that we can complain less grossly about it when it's missing.
344 local wheres_nechung=$(which nechung 2>/dev/null)
345 if [ -z "$wheres_nechung" ]; then
346 echo "The nechung oracle program cannot be found. You may want to consider"
347 echo "rebuilding the feisty meow applications with this command:"
348 echo "bash $FEISTY_MEOW_SCRIPTS/generator/produce_feisty_meow.sh"
354 # recreates all the generated files that the feisty meow scripts use.
355 function regenerate() {
356 # do the bootstrapping process again.
357 echo "regenerating feisty meow script environment."
358 bash $FEISTY_MEOW_SCRIPTS/core/reconfigure_feisty_meow.sh
360 # force a full reload by turning off sentinel variable and alias.
361 # the nethack one is used by fred's customizations.
362 # interesting note perhaps: found that the NETHACKOPTIONS variable was
363 # not being unset correctly when preceded by an alias. split them up
364 # like they are now due to that bug.
365 unset -v CORE_ALIASES_LOADED FEISTY_MEOW_LOADING_DOCK NECHUNG NETHACKOPTIONS
366 unset -f function_sentinel
367 # reload feisty meow environment in current shell.
368 source $FEISTY_MEOW_SCRIPTS/core/launch_feisty_meow.sh
369 # run nechung oracle to give user a new fortune.
373 # copies a set of custom scripts into the proper location for feisty meow
374 # to merge their functions and aliases with the standard set.
375 function recustomize()
378 if [ -z "$user" ]; then
379 # use our default example user if there was no name provided.
382 if [ ! -d "$FEISTY_MEOW_APEX/customizing/$user" ]; then
383 echo "The customization folder provided for $user should be:"
384 echo " '$FEISTY_MEOW_APEX/customizing/$user'"
385 echo "but that folder does not exist. Skipping customization."
388 regenerate >/dev/null
389 pushd "$FEISTY_MEOW_LOADING_DOCK/custom" &>/dev/null
390 incongruous_files="$(bash "$FEISTY_MEOW_SCRIPTS/files/list_non_dupes.sh" "$FEISTY_MEOW_APEX/customizing/$user" "$FEISTY_MEOW_LOADING_DOCK/custom")"
392 #echo "the incongruous files list is: $incongruous_files"
393 # disallow a single character result, since we get "*" as result when nothing exists yet.
394 if [ ${#incongruous_files} -ge 2 ]; then
395 echo "cleaning unknown older overrides..."
396 perl "$FEISTY_MEOW_SCRIPTS/files/safedel.pl" $incongruous_files
400 echo "copying custom overrides for $user"
401 mkdir -p "$FEISTY_MEOW_LOADING_DOCK/custom" 2>/dev/null
402 perl "$FEISTY_MEOW_SCRIPTS/text/cpdiff.pl" "$FEISTY_MEOW_APEX/customizing/$user" "$FEISTY_MEOW_LOADING_DOCK/custom"
403 if [ -d "$FEISTY_MEOW_APEX/customizing/$user/scripts" ]; then
404 echo "copying custom scripts for $user"
405 \cp -R "$FEISTY_MEOW_APEX/customizing/$user/scripts" "$FEISTY_MEOW_LOADING_DOCK/custom/"
411 # generates a random password where the first parameter is the number of characters
412 # in the password (default 20) and the second parameter specifies whether to use
413 # special characters (1) or not (0).
414 # found function at http://legroom.net/2010/05/06/bash-random-password-generator
415 function random_password()
417 [ "$2" == "0" ] && CHAR="[:alnum:]" || CHAR="[:graph:]"
418 cat /dev/urandom | tr -cd "$CHAR" | head -c ${1:-32}
422 # a wrapper for the which command that finds items on the path. some OSes
423 # do not provide which, so we want to not be spewing errors when that
428 which which &>/dev/null
429 if [ $? -ne 0 ]; then
430 # there is no which command here. we produce nothing due to this.
433 echo $(which $to_find)
436 #hmmm: improve this by not adding the link
437 # if already there, or if the drive is not valid.
438 function add_cygwin_drive_mounts() {
439 for i in c d e f g h q z ; do
440 ln -s /cygdrive/$i $i
444 ############################
446 # takes a file to modify, and then it will replace any occurrences of the
447 # pattern provided as the second parameter with the text in the third
449 function replace_pattern_in_file()
451 local file="$1"; shift
452 local pattern="$1"; shift
453 local replacement="$1"; shift
454 if [ -z "$file" -o -z "$pattern" -o -z "$replacement" ]; then
455 echo "replace_pattern_in_file: needs a filename, a pattern to replace, and the"
456 echo "text to replace that pattern with."
459 sed -i -e "s%$pattern%$replacement%g" "$file"
462 # similar to replace_pattern_in_file, but also will add the new value
463 # when the old one did not already exist in the file.
464 function replace_if_exists_or_add()
466 local file="$1"; shift
467 local phrase="$1"; shift
468 local replacement="$1"; shift
469 if [ -z "$file" -o ! -f "$file" -o -z "$phrase" -o -z "$replacement" ]; then
470 echo "replace_if_exists_or_add: needs a filename, a phrase to replace, and the"
471 echo "text to replace that phrase with."
474 grep "$phrase" "$file" >/dev/null
475 # replace if the phrase is there, otherwise add it.
476 if [ $? -eq 0 ]; then
477 replace_pattern_in_file "$file" "$phrase" "$replacement"
479 # this had better be the complete line.
480 echo "$replacement" >>"$file"
484 ############################
486 # finds a variable (first parameter) in a particular property file
487 # (second parameter). the expected format for the file is:
489 function seek_variable()
491 local find_var="$1"; shift
492 local file="$1"; shift
493 if [ -z "$find_var" -o -z "$file" -o ! -f "$file" ]; then
494 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
499 if [ ${#line} -eq 0 ]; then continue; fi
500 # split the line into the variable name and value.
501 IFS='=' read -a assignment <<< "$line"
502 local var="${assignment[0]}"
503 local value="${assignment[1]}"
504 if [ "${value:0:1}" == '"' ]; then
505 # assume the entry was in quotes and remove them.
506 value="${value:1:$((${#value} - 2))}"
508 if [ "$find_var" == "$var" ]; then
514 # finds a variable (first parameter) in a particular XML format file
515 # (second parameter). the expected format for the file is:
516 # ... name="varX" value="valueX" ...
517 function seek_variable_in_xml()
519 local find_var="$1"; shift
520 local file="$1"; shift
521 if [ -z "$find_var" -o -z "$file" -o ! -f "$file" ]; then
522 echo "seek_variable_in_xml: needs two parameters, firstly a variable name, and"
523 echo "secondly an XML file where the variable's value will be sought."
528 if [ ${#line} -eq 0 ]; then continue; fi
529 # process the line to make it more conventional looking.
530 line="$(echo "$line" | sed -e 's/.*name="\([^"]*\)" value="\([^"]*\)"/\1=\2/')"
531 # split the line into the variable name and value.
532 IFS='=' read -a assignment <<< "$line"
533 local var="${assignment[0]}"
534 local value="${assignment[1]}"
535 if [ "${value:0:1}" == '"' ]; then
536 # assume the entry was in quotes and remove them.
537 value="${value:1:$((${#value} - 2))}"
539 if [ "$find_var" == "$var" ]; then
545 ############################
547 # goes to a particular directory passed as parameter 1, and then removes all
548 # the parameters after that from that directory.
549 function push_whack_pop()
551 local dir="$1"; shift
552 pushd "$dir" &>/dev/null
553 rm -rf $* &>/dev/null
559 while [ $# -gt 0 ]; do
561 if [ ! -f "$arg" -a ! -d "$arg" ]; then
562 echo "failure to find a file or directory named '$arg'."
566 # first we will capture the output of the character replacement operation for reporting.
567 # this is done first since some filenames can't be properly renamed in perl (e.g. if they
568 # have pipe characters apparently).
569 intermediate_name="$(bash "$FEISTY_MEOW_SCRIPTS/files/replace_spaces_with_underscores.sh" "$arg")"
570 local saw_intermediate_result=0
571 if [ -z "$intermediate_name" ]; then
572 # make sure we report something, if there are no further name changes.
573 intermediate_name="'$arg'"
575 # now zap the first part of the name off (since original name isn't needed).
576 intermediate_name="$(echo $intermediate_name | sed -e 's/.*=> //')"
577 saw_intermediate_result=1
580 # first we rename the file to be lower case.
581 actual_file="$(echo $intermediate_name | sed -e "s/'\([^']*\)'/\1/")"
582 final_name="$(perl $FEISTY_MEOW_SCRIPTS/files/renlower.pl "$actual_file")"
583 local saw_final_result=0
584 if [ -z "$final_name" ]; then
585 final_name="$intermediate_name"
587 final_name="$(echo $final_name | sed -e 's/.*=> //')"
590 #echo intermed=$saw_intermediate_result
591 #echo final=$saw_final_result
593 if [[ $saw_intermediate_result != 0 || $saw_final_result != 0 ]]; then
594 # printout the combined operation results.
595 echo "'$arg' => $final_name"
602 # new breed of definer functions goes here. still in progress.
604 # defines an alias and remembers that this is a new or modified definition.
605 # if the feisty meow codebase is unloaded, then so are all the aliases that
607 function define_yeti_alias()
609 # if alias exists already, save old value for restore,
610 # otherwise save null value for restore,
611 # have to handle unaliasing if there was no prior value of one
613 # add alias name to a list of feisty defined aliases.
615 #hmmm: first implem, just do the alias and get that working...
622 # defines a variable within the feisty meow environment and remembers that
623 # this is a new or modified definition. if the feisty meow codebase is
624 # unloaded, then so are all the variables that were defined.
625 # this function always exports the variables it defines.
626 # function define_yeti_variable()
628 ## if variable exists already, save old value for restore,
629 ## otherwise save null value for restore,
630 ## have to handle unsetting if there was no prior value of one
632 ## add variable name to a list of feisty defined variables.
634 ##hmmm: first implem just sets it up and exports the variable.
635 ## i.e., this method always exports.
644 # just shows a separator line for an 80 column console, or uses the first
645 # parameter as the number of columns to expect.
649 if [ -z "$count" ]; then
654 for ((i=0; i < $count - 1; i++)); do
660 # alias for separator.
668 function function_sentinel() { return 0; }
670 if [ ! -z "$SHELL_DEBUG" ]; then echo "feisty meow function definitions done."; fi
674 # test code for set_var_if_undefined.
676 if [ $run_test != 0 ]; then
677 echo running tests on set_var_if_undefined.
679 set_var_if_undefined flagrant forknordle
680 check_result "testing if defined variable would be whacked"
681 if [ $flagrant != petunia ]; then
682 echo set_var_if_undefined failed to leave the test variable alone
685 unset bobblehead_stomper
686 set_var_if_undefined bobblehead_stomper endurance
687 if [ $bobblehead_stomper != endurance ]; then
688 echo set_var_if_undefined failed to set a variable that was not defined yet