====== Bash Functions ====== ==== index # Print the position of $2 in $1 ==== index() #@ Print the position of $2 in $1 { #@ USAGE: index STRING SUBSTRING local idx case $1 in *$2*) idx=${1%%$2*} echo $(( ${#idx} + 1 )) ;; *) echo 0 ;; esac } [[http://www.linkedin.com/groups/Fridays-function-index-3716796.S.237745984?view=&srchtype=discussedNews&gid=3716796&item=237745984&type=member&trk=eml-anet_dig-b_pd-ttl-cn&ut=0kcr73WwfdW5I1 | From Article]] ==== die # Exit with error code and optional message ==== die() #@ Exit with error code and optional message { #@ USAGE: die RETURN_CODE [MESSAGE] result=$1 shift [ -n "$*" ] && printf "%s\n" "$*" >&2 exit "$result" } [[ http://www.linkedin.com/groups/Fridays-function-die-3716796.S.236067929?qid=da8e8fcc-4fda-480a-91a1-3ef360d90e53&trk=group_most_popular_guest-0-b-ttl&goback=.gde_3716796_member_237745984.gmp_3716796 | From Article ]] ==== Place SUBSTRING over STRING beginning at OFFSET ==== overlay() #@ Place SUBSTRING over STRING beginning at OFFSET { #@ USAGE: overlay VARNAME SUBSTRING OFFSET local varname=$1 substr=$2 start=$3 string eval "string=\${$varname}" left=${string:0:start} right=${string:start+${#substr}} printf -v "$varname" %s%s%s "$left" "$substr" "$right" } [[ http://www.linkedin.com/groups/Fridays-function-overlay-3716796.S.241936021?view=&gid=3716796&type=member&item=241936021&trk=eml-anet_dig-b_nd-pst_ttle-cn | From Article ]] ==== Print the ASCII value of the first character ==== asc() #@ Print the ASCII value of the first character of each argument { #@ USAGE: asc STRING ... for char do printf "%d${EOV-\n}" "'$char" done } [[ http://www.linkedin.com/groups/Fridays-function-asc-Print-ASCII-3716796.S.252009597?view=&gid=3716796&type=member&item=252009597&trk=eml-anet_dig-b_nd-pst_ttle-cn | From Article ]] ==== Print argument in reverse ==== revword() #@ print each argument with bytes reversed for w do len=${#w} w2= n=0 while (( ${#w2} < len )) do w2=${w:n++:1}$w2 done printf "%s\n" "$w2" done [[ http://www.linkedin.com/groups/Fridays-function-revword-3716796.S.253755071?view=&gid=3716796&type=member&item=253755071&trk=eml-anet_dig-b_nd-pst_ttle-cn | From Article ]] ==== Add directory or directories to PATH ==== addpath() #@ add directory or directories to $PATH { #@ USAGE: addpath DIR ... local prefix=0 quiet=0 OPTIND=1 p while getopts iq var do case "$var" in i) prefix=1 ;; q) quiet=1 ;; esac done shift $(( $OPTIND - 1 )) for p do p=${p%"${p##*[!/]}"} ## remove trailing slashes case $p in ""|.) continue ;; esac case :$PATH: in *:$p:*) (( quiet == 0 )) && echo "addpath: $p already in path" >&2 continue ;; esac if [ -d "$p" ] then (( prefix == 1 )) && PATH=$p:$PATH || PATH=$PATH:$p else [ $quiet -eq 0 ] && echo "addpath: $p is not a directory" >&2 fi done export PATH ## probably unnecessary } [[ http://www.linkedin.com/groups/Fridays-function-addpath-Add-one-3716796.S.255801510 | From Article ]] ==== Return random date in given range of years ==== random_date() #@ Return random date in given range of years { #@ USAGE: random_date FIRST LAST [VAR] #@ Global variables set: random_date [VAR] local first=${1:-1752} last=${2:-2100} var=$3 declare -i year month day dim year=$(( RANDOM % (last-first) + first )) month=$(( RANDOM % 12 + 1 )) days_in_month dim "$month" "$year" day=$(( RANDOM % dim + 1 )) printf -v random_date "%d-%02d-%02d" "$year" "$month" "$day" is_var "$var" && printf -v "$var" %s "$random_date" || printf "%s\n" "$random_date" } [[ http://www.linkedin.com/groups/Fridays-function-randomdate-Return-random-3716796.S.5799573907065286656 | From Article ]] ==== Check if it is factor ==== is_factor() #@ Return successfully if $2 is a factor of $1 { #@ USAGE: is_factor NUMBER FACTOR local number=$1 factor=$2 (( ((number / factor) * factor) == number )) } [[ http://www.linkedin.com/groups/Fridays-function-isfactor-Return-successfully-3716796.S.5794561860833390593 | From Article ]] ==== Check if it is factor ==== dec2bin() #@ Convert decimal integer to binary optionally padding with zeroes { #@ USAGE: dec2bin INT [WIDTH] [VAR] local val=$1 _w=$2 var=$3 _b=2 _r bin if (( $# == 1 )) || is_var "$2" ## is_var() posted last month then _w=1 fi while ((val)) do _r=$(( $val % $_b )) bin=$_r$bin; val=$(( val / _b )) done printf -v bin "%0${_w}d" "$((10#$bin))" is_var "$var" && printf -v "$var" %s "$bin" || printf "%s\n" "$bin" } [[ http://www.linkedin.com/groups/Fridays-functon-dec2bin-Convert-decimal-3716796.S.277082108 | From Article ]] ==== List running process matching args ==== psg() #@ Show all running processes matching ARG[s] { #@ USAGE: psg STRING ... local ss for ss do ## Enclose first character in brackets so grep doesn't show its own process ss=\[${ss:0:1}\]${ss#?} ps -ef | grep "$ss" [ $# -gt 1 ] && echo done } [[ http://www.linkedin.com/groups/Fridays-function-psg-Show-all-3716796.S.5827514953933824001?view=&gid=3716796&type=member&item=5827514953933824001&trk=eml-anet_dig-b_nd-pst_ttle-cn | From Article ]] ==== Print the result of arithmetical calulation ==== calc() #@ Print the result of arithmetical calulation { #@ USAGE: calc EXPRESSION awk 'BEGIN {print '"${*//x/*}"'}' } [[ http://www.linkedin.com/groups/Fridays-function-calc-Print-result-3716796.S.5832542139925430274?view=&srchtype=discussedNews&gid=3716796&item=5832542139925430274&type=member&trk=eml-anet_dig-b_pd-ttl-cn&fromEmail=&ut=04XvycE_RsJm41 | From Article ]] ==== Print lines on screen descending from the current point ==== lines() #@ Print lines on screen descending from the current point { #@ USAGE: [printat ROW COL [STRING];] lines STRING ... local cu_save=$'\e[s' cu_restore=$'\e[u' cu_down=$'\e[B' printf "$cu_restore$cu_down$cu_save%s" "$@" } [[ https://www.linkedin.com/groups/Fridays-function-lines-Print-lines-3716796.S.5900869707560415236?view=&item=5900869707560415236&type=member&gid=3716796&trk=eml-b2_anet_digest-hero-1-hero-disc-disc-0&midToken=AQG8JYIVdmXjvA&fromEmail=fromEmail&ut=0fjZG80YW_UCk1 | From Article ]] ==== Integer or Decimal ==== case ${1#-} in *[!0-9.]*|.) echo not an integer or float ;; *.*) echo float ;; *) echo int ;; esac - OR - i=$1 let 'i++' if [ $? -eq 0 ] # check in not error returned then echo "integer" else echo "not integer" fi [[ https://www.linkedin.com/groups/How-can-i-verify-if-3716796.S.5862974732210556931?view=&item=5862974732210556931&type=member&gid=3716796&trk=eml-b2_anet_digest-null-2-null&fromEmail=fromEmail&ut=3KLlfwU1D4UCk1 | From Article ]] ==== floating point multiplication ==== fpmul() #@ Perform floating-point multiplication in the shell { #@ USAGE: fpmul [VAR] NUM.DEC ... local _var= _places _tot _neg _n _int _dec _df _fpmul if [[ ${1^^} =~ ^[A-Z_][A-Z0-9_]*$ ]] then _var=$1 shift fi _places= _tot=1 _neg= for _n do ## 2 negatives make a positive case $_n in -*) [ "$_neg" = '-' ] && _neg= || _neg='-' _n=${_n#-} ;; esac ## Check for non-numeric characters case $_n in *[!0-9.]*) return 1 ;; esac ## count the number of decimal _places, ## then remove the decimal point case $_n in .*) _int= _dec=${_n#?} _places=$_places$_dec _n=$_dec ;; *.*) _dec=${_n#*.} _int=${_n%.*} _places=$_places$_dec _n=$_int$_dec ;; esac ## remove leading zeroes while : do case $_n in ""|0) _n=0 _fpmul=0 return ;; 0*) _n=${_n#0} ;; *) break;; esac done ## multiply by the previous _total _tot=$(( $_tot * ${_n:-0} )) ## report any overflow error case $_tot in -*) printf "fpmul: overflow error: %s\n" "$_tot" >&2 return 1 ;; esac done while [ ${#_tot} -lt ${#_places} ] do _tot=0$_tot done _df= while [ ${#_df} -lt ${#_places} ] do left=${_tot%?} _df=${_tot#$left}$_df _tot=$left done _fpmul=$_tot${_df:+.$_df} ## remove trailing zeroes or decimal points while : do case $_fpmul in *.*[0\ ]|*.) _fpmul=${_fpmul%?} ;; .*) _fpmul=0$_fpmul ;; *) break ;; esac done [[ $_var ]] && printf -v "$_var" %s "$_fpmul" || printf '%s\n' "$_fpmul" } num.dec [[http://www.linkedin.com/groups/Fridays-function-fpmul-Perform-floatingpoint-3716796.S.5921339472191987716?view=&item=5921339472191987716&type=member&gid=3716796&trk=eml-b2_anet_digest-hero-1-hero-disc-disc-0&midToken=AQG8JYIVdmXjvA&fromEmail=fromEmail&ut=3_RJ7vAOch56s1|From article]] ==== show array ==== ashow() #@ Display contents of array[s] { #@ USAGE: ashow ARRAYNAME ... local _arg _num=0 for arg do :; ((_num++)) && echo :; declare -n array=$arg :; [[ -n ${array[*]} ]] && printf '%s\n' "${array[@]}" done } [[https://www.linkedin.com/groups/Fridays-function-ashow-Display-contents-3716796.S.5918816399794409474?view=&item=5918816399794409474&type=member&gid=3716796&trk=eml-b2_anet_digest-hero-4-hero-disc-disc-0&midToken=AQG8JYIVdmXjvA&fromEmail=fromEmail&ut=19mP4Lva0K56s1|From Article]] ==== Reverse Word ==== revword() #@ Reverse the order of characters in STRING { #@ USAGE: revword STRING [VAR] local _n _word=$1 _var=$2 _len _r _rw= _l while read -n1 _l do _rw=$_l$_rw done <<< "$_word" [[ ${_var^^} =~ ^[A-Z_][A-Z0-9_]*$ ]] && printf -v "$_var" %s "$_rw" || printf '%s\n' "$_rw" } [[ https://www.linkedin.com/groups/Fridays-function-revword-Reverse-order-3716796.S.5916260779903975428?view=&item=5916260779903975428&type=member&gid=3716796&trk=eml-b2_anet_digest-hero-1-hero-disc-disc-0&midToken=AQG8JYIVdmXjvA&fromEmail=fromEmail&ut=13sqjyjg1356s1 | From Article ]] ==== Trim Spaces ==== trim() #@ Trim spaces (or char in $2) from both ends of $1 { #@ USAGE: trim STRING [CHAR [VAR]] local _trim_string _trim=$1 _char=${2:- } _var=$3 _trim_string=${_trim##*[!$_char]} _trim=${_trim%"$_trim_string"} _trim_string=${_trim%%[!$_char]*} _trim=${_trim#"$_trim_string"} is_var "$_var" && printf -v "$_var" %s "$_trim" || printf '%s\n' "$_trim" } [[ https://www.linkedin.com/groups/Fridays-function-trim-Trim-spaces-3716796.S.5908643378429460481?view=&item=5908643378429460481&type=member&gid=3716796&trk=eml-b2_anet_digest-hero-1-hero-disc-disc-0&midToken=AQG8JYIVdmXjvA&fromEmail=fromEmail&ut=2lgJiLIHdb56s1 | From Article ]]