onlyforbopi
1/2/2017 - 8:48 AM

Linux.Bash.String.Functions

Linux.Bash.String.Functions #bash #linux #string #function #toupper #tolower #validate #validateip #validateemail

BASH_STRING_FUNCTIONS

#!/bin/bash

validator() {
  printf "* %-48s" "$1"
  echo "$1" | egrep --quiet "^([A-Za-z]+[A-Za-z0-9]*((\.|\-|\_)?[A-Za-z]+[A-Za-z0-9]*){1,})@(([A-Za-z]+[A-Za-z0-9]*)+((\.|\-|\_)?([A-Za-z]+[A-Za-z0-9]*)+){1,})+\.([A-Za-z]{2,})+"
  [ $? -eq 0 ] && printf "\e[1;32m[pass]\e[m" || printf "\e[1;31m[fail]\e[m"
  echo
}

echo
echo "a simple email validator in shell"
echo
echo "online validator: http://emailregex.com/"
echo "RFC: http://emailregex.com/email-validation-summary/"
echo

echo
echo "### expected result: valid"
echo

validator "valid@example.com"
validator "vali.d@example.com"
validator "va-lid@example.com"
validator "v-a-l-i-d@example.com"
validator "v.a-lid@example.com"
validator "v.ali-d@example.com"
validator "v_ali-d@example.com"
validator "va_li-d@example.com"
validator "v_a_li_d@example.com"
validator "v.ali-d@example.com"
validator "v.ali.d@example.com"
validator "v0.ali.d@example.com"
validator "v0.ali.d1@example.com"
validator "valid@e-x_ample.com"
validator "valid@e.x-ample.c.om"
validator "valid@e.xample.c.a.tw"

echo
echo "### expected result: invalid"
echo

validator "-invalid@example.com"
validator ".invalid@example.com"
validator "_invalid@example.com"
validator "inv alid@example.com"
validator "invalid@exa mple.com"
validator "inv.-alid@example.com"
validator "inv-.-alid@example.com"
validator "invali-.-d@example.com"
validator "inval..id@example.com"
validator "inva--lid@example.com"
validator "inval_-id@example.com"
validator "inval-.id@example.com"
validator "invalid.@example.com"
validator "invalid_@example.com"
validator "invalid-@example.com"
validator "invalid.0@example.com"
validator "invalid.1@example.com"
validator "0.invali.d@example.com"
validator "0.invali.1@example.com"
validator "inv.ali.0d@example.com"
validator "invalid@example.c-.om"
validator "invalid@example._com"
validator "invalid@e-x._ample.com"
validator "invalid@e-.x_ample.com"
validator "invalid@e.-x_ample.com"
validator "invalid@example.c"
validator "invalid@example._"
validator "invalid@exampl.0e"
validator "invalid@exampl.e1"
validator "invalid@exampl.1"
validator "invalid@exampl.1a.b.c"

echo
echo "### END"
echo
function valid_ip()
{
local  ip=$1
local  stat=1

if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
    OIFS=$IFS
    IFS='.'
    ip=($ip)
    IFS=$OIFS
    [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
        && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
    stat=$?
fi
return $stat
}


valid_ip 8.8.8.8
echo $?




ip=10.10.50.53

ipvalid() {
  # Set up local variables
  local ip=${1:-1.2.3.4}
  local IFS=.; local -a a=($ip)
  # Start with a regex format test
  [[ $ip =~ ^[0-9]+(\.[0-9]+){3}$ ]] || return 1
  # Test values of quads
  for quad in {0..3}; do
    [[ "${a[$quad]}" -gt 255 ]] && return 1
  done
  return 0
}

if ipvalid "$ip"; then
  echo "success ($ip)"
  exit 0
else
  echo "fail ($ip)"
  exit 1
fi
validatedate() {


	
	if 	[[ "$1" =~ ^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$ ]]
	
		#           |^^^^^^^^ ^^^^^^ ^^^^^^  ^^^^^^ ^^^^^^^^^^ ^^^^^^ |
		#           |   |     ^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^ |
		#           |   |          |                   |              |
		#           |   |           \                  |              |
		#           | --year--   --month--           --day--          |
		#           |          either 01...09      either 01..09     end of line
		# start of line            or 10,11,12         or 10..29
		#                                              or 30, 31	
	
	
	then
		echo "yes"
		return 0
	else
		echo "no"
		return 1
	fi
}

# Called as:
validatedate 19820214
1. bash_strlen()           : Calculates the length of string
2. toupper()               : Converts string to uppercase
3. tolower()               : Converts string to lowercase
4. isalpha()               : Tests if entire string is alphabetic
5. char2int()              : Converts char to integer (decimal)
6. last_char()             : Returns last char of string 
7. string2octal()          : Converts a string to Octal
8. string_split()          : Split a string based on delimiter
9. string_cat()            : Concatenates two strings
10.string_lim_cat()        : Concatenates a certain amount of characters
11.string_compare()        : Compares two strings
12.string_lim_cmp()        : Compares maximum of n characters
13.validatedate()          : Validates a date of the yyyymmdd format
14.validateip()            : Validates an ip address
15.validateemail()         : Validates an email address
#:docstring strncat:
# Usage: strncat s1 s2 $n
# 
# Line strcat, but strncat appends a maximum of n characters from the value
# of variable s2.  It copies fewer if the value of variabl s2 is shorter
# than n characters.  Echoes result on stdout.
#
# Example:
#    a=foo
#    b=barbaz
#    strncat a b 3
#    echo $a
#    => foobar
#
#:end docstring:

###;;;autoload
function strncat ()
{
    local s1="$1"
    local s2="$2"
    local -i n="$3"
    local s1_val s2_val

    s1_val=${!s1}                       # ==> indirect variable expansion
    s2_val=${!s2}

    if [ ${#s2_val} -gt ${n} ]; then
       s2_val=${s2_val:0:$n}            # ==> substring extraction
    fi

    eval "$s1"=\'"${s1_val}${s2_val}"\'
    # ==> eval $1='${s1_val}${s2_val}' avoids problems,
    # ==> if one of the variables contains a single quote.
}
#:docstring strcmp:
# Usage: strcmp $s1 $s2
#
# Strcmp compares its arguments and returns an integer less than, equal to,
# or greater than zero, depending on whether string s1 is lexicographically
# less than, equal to, or greater than string s2.
#:end docstring:

###;;;autoload
function strcmp ()
{
    [ "$1" = "$2" ] && return 0

    [ "${1}" '<' "${2}" ] > /dev/null && return -1

    return 1
}
_lastchar() { #return last char of a string 
   [ -z "${1}" ] && return 1 
   for i; do :; done 
   _1stchar__substr="${i%?}" 
   printf "%s\\n" "${i#$_1stchar__substr}" 
} 
#==================================================== Example ==== 
#_lastchar test #print 't' 
#================================================================= 
# Convert to uppercase
function toupper()
{
  # Function: toupper()
  # Description: Converts string to upper case
  # Input: string or var containing string
  # Output: string (uppercased)
  # Usage: See below

						#  Converts string(s) passed as argument(s)
						#+ to uppercase

  if [ -z "$1" ]       	#  If no argument(s) passed,
  then                 	#+ send error message
    echo "(null)"      	#+ (C-style void-pointer error message)
    return             	#+ and return from function.
  fi  

  echo "$@" | tr a-z A-Z
  # Translate all passed arguments ($@).

  return

# Use command substitution to set a variable to function output.
# For example:
#    oldvar="A seT of miXed-caSe LEtTerS"
#    newvar=`tolower "$oldvar"`
#    echo "$newvar"    # a set of mixed-case letters
#
}
# Convert to lowercase
function tolower()
{
  # Function: tolower()
  # Description: Converts string to lower case
  # Input: string or var containing string
  # Output: string (lowercased)
  # Usage: See below

						#  Converts string(s) passed as argument(s)
						#+ to uppercase

  if [ -z "$1" ]       	#  If no argument(s) passed,
  then                 	#+ send error message
    echo "(null)"      	#+ (C-style void-pointer error message)
    return             	#+ and return from function.
  fi  

  echo "$@" | tr A-Z a-z
  # Translate all passed arguments ($@).

  return

# Use command substitution to set a variable to function output.
# For example:
#    oldvar="A seT of miXed-caSe LEtTerS"
#    newvar=`tolower "$oldvar"`
#    echo "$newvar"    # a set of mixed-case letters
#
}
bash_strlen() 
{ 
  # Function        : bash_strlen()
  # Description     : Calculates the length of a function
  # Input           : String or variable containing string
  # Output          : Length of string
  # Usage           : bash_strlen $x or bash_strlen "alalalal"  
  # Operation       : print the length of a string, return 1 on failure 
     [ -z "${1}" ] && return 1 
     printf "%s\\n" "${#1}" 
} 
#==================================================== Example ==== 
#_strlen "hello world!" #returns "12" 
#================================================================= 


#:docstring strlen:
# Usage: strlen s
#
# Strlen returns the number of characters in string literal s.
#:end docstring:

###;;;autoload
function strlen ()
{
    eval echo "\${#${1}}"
    # ==> Returns the length of the value of the variable
    # ==> whose name is passed as an argument.
    
    
###################################################################
# Ways to calculate strlen
${#VAR}
${#str_var}  

#$ mystring="one two three four five"
#j$ echo "string length: ${#mystring}"

#SO="stackoverflow"
#$ echo -n $SO | wc -c
isalpha2 ()            # Tests whether *entire string* is alphabetic.
{                      # From "isalpha.sh" example.
  [ $# -eq 1 ] || return $FAILURE

  case $1 in
  *[!a-zA-Z]*|"") return $FAILURE;;
  *) return $SUCCESS;;
  esac                 # Thanks, S.C.
}
_str2octal() { #convert a string to octal 
   [ -z "${1}" ] && return 1 
   printf "%s" "${@}" | od -v -A n -t o1 | \ 
       sed "s:^ ::" | tr -d "\n" 
} 
#==================================================== Example ==== 
#hello="hello" 
#hello="$(_str2octal "${hello}")" 
#printf "%s\\n" "${hello}"   #prints "150 145 154 154 157" 
#================================================================= 


_str2octal_escaped() { #convert a string to escaped octal 
     [ -z "${1}" ] && return 1 
     printf "%s" "${@}" | od -v -A n -t o1 | \ 
         sed "s/ *\([0-9]*\) */\\\\\1/g" | tr -d "\n" 
 } 
 #==================================================== Example ==== 
 #hello="hello" 
 #hello="$(_str2octal "${hello}")" 
 #printf "%s\\n" "${hello}"   #prints "\150\145\154\154\157" 
 #================================================================= 
 
_char2int() { 
    [ -z "${1}" ] && return 1 
    printf '%d' "'${*}" 
} 
#==================================================== Example ==== 
#num="$(_char2int a)" 
#printf "%s\\n" "${num}" #prints 97 
#================================================================= 



num="$(_char2int c)" 
printf "%s\\n" "${num}" #prints 97 
#:docstring strncmp:
# Usage: strncmp $s1 $s2 $n
# 
# Like strcmp, but makes the comparison by examining a maximum of n
# characters (n less than or equal to zero yields equality).
#:end docstring:

###;;;autoload
function strncmp ()
{
    if [ -z "${3}" -o "${3}" -le "0" ]; then
       return 0
    fi
   
    if [ ${3} -ge ${#1} -a ${3} -ge ${#2} ]; then
       strcmp "$1" "$2"
       return $?
    else
       s1=${1:0:$3}
       s2=${2:0:$3}
       strcmp $s1 $s2
       return $?
    fi
}
#:docstring strcat:
# Usage: strcat s1 s2
#
# Strcat appends the value of variable s2 to variable s1. 
#
# Example:
#    a="foo"
#    b="bar"
#    strcat a b
#    echo $a
#    => foobar
#
#:end docstring:

###;;;autoload   ==> Autoloading of function commented out.
function strcat ()
{
    local s1_val s2_val

    s1_val=${!1}                        # indirect variable expansion
    s2_val=${!2}
    eval "$1"=\'"${s1_val}${s2_val}"\'
    # ==> eval $1='${s1_val}${s2_val}' avoids problems,
    # ==> if one of the variables contains a single quote.
}
function split () {
	local IFS="$1"
	builtin echo $(for x in $2; do builtin echo -n "$x "; done);
}
12 _1stchar() { #return first char of a string 
13     [ -z "${1}" ] && return 1 
14     _1stchar__substr="${1#?}" 
15     printf "%s\\n" "${1%$_1stchar__substr}" 
16 } 
17 #==================================================== Example ==== 
18 #_1stchar test #print 't' 
19 #================================================================= 
20 
33 _alphanum() { #check for alphanum strings 
34   [ -z "${1}" ] && return 1 
35 
 
36   #remove unacceptable chars 
37   _alphanum__compressed="$(printf "%s" "${1}" | sed -e 's:[^[:alnum:]]::g')" 
38   [ X"${_alphanum__compressed}" = X"${1}" ] 
39 } 
40 #==================================================== Example ==== 
41 #printf "%s" "Enter input: " 
42 #read input 
43 #if ! _alphanum "${input}" ; then 
44     #printf "%s\\n" "Your input must consist of only letters and numbers." >&2 
45     #exit 1 
46 #else 
47     #printf "%s\\n" "Input is valid." 
48 #fi 
49 #exit 0 
189 _decode64() { #decode a base64 string 
190     [ ! -t 0 ] && set -- "${@}" "$(cat)" 
191     [ -z "${1}" ] && return 1 
192     if command -v "base64" >/dev/null 2>&1; then 
193         printf "%s\\n" "${@}" | base64 -d 
194     elif command -v "openssl" >/dev/null 2>&1; then 
195         printf "%s\\n" "${@}" | openssl enc -base64 -d 
196     elif command -v "awk" >/dev/null 2>&1 && (command -v "uudecode" || command -v "busybox") >/dev/null 2>&1; then 
197         if command -v "uudecode" >/dev/null 2>&1; then 
198             uudecode__bin="uudecode" 
199         elif command -v "busybox"  >/dev/null 2>&1; then 
200             uudecode__bin="busybox uudecode" 
201         fi 
202         _decode64_awk() { [ ! -t 0 ] && set -- "${@}" "$(cat)" 
203           [ -z "${1}" ] && return 1 
204           printf "%s\\n" "${@}" | sed 's/=//g' | ( 
205             printf "begin 644 -\\n"; awk 'function _decode64_awk() { 
206               inp=1; out=""; while (getline) { for(i=1; i<=length($0); i++) { 
207                   c=substr(uu,index(b64,substr($0,i,1)),1); 
208                   inp++; out=(out c); if (inp==61) { 
209                     print "M" out; inp=1; out=""; }}} 
210               if (length(out)) { printf "%c", (32+3*length(out)/4); print out; }} 
211             BEGIN { b64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" 
212               uu="`!\"#$%&'\''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_" 
213               _decode64_awk(); exit; }' 
214             printf "%s\\n%s\\n" '`' 'end' #' 
215           ) | $uudecode__bin 
216         } 
217         printf "%s\\n" "${@}" | _decode64_awk 
218     else 
219         _decode64_sh() { [ ! -t 0 ] && set -- "${@}" "$(cat)" 
220             _decode64_sh__b64='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' 
221             _decode64_sh__n="0"; _decode64_sh__v="0"; _decode64_sh__args="$@" 
222             while [ "${_decode64_sh__args}" ]; do #process char by char 
223                 _decode64_sh__char="${_decode64_sh__args%${_decode64_sh__args#?}}" 
224                 case "${_decode64_sh__char}" in 
225                     '\n') continue ;; 
226                      '=') _decode64_sh__v="$(($_decode64_sh__v << 6))" ;; 
227                        *) _decode64_sh__char="${_decode64_sh__b64#*$_decode64_sh__char}" 
228                           _decode64_sh__char="$((${#_decode64_sh__b64}-${#_decode64_sh__char}))" 
229                           if [ "${_decode64_sh__char}" -eq "0" ]; then 
230                             [ X"${_decode64_sh__args}" = X"${_decode64_sh__char}" ] &&\ 
231                                 _decode64_sh__args='' || _decode64_sh__args="${_decode64_sh__args#?}" 
232                             continue 
233                           fi 
234                           _decode64_sh__v="$(($_decode64_sh__v << 6 | $_decode64_sh__char-1))" 
235                 esac 
236                 _decode64_sh__n="$(($_decode64_sh__n+1))" 
237                 if [ "${_decode64_sh__n}" -eq "4" ]; then 
238                     _decode64_sh__s="16"; while [ "${_decode64_sh__s}" -gt "-1" ]; do 
239                         _decode64_sh__char="$(($_decode64_sh__v >> $_decode64_sh__s & 255))" 
240                         printf \\$(($_decode64_sh__char/64*100+$_decode64_sh__char%64/8*10+$_decode64_sh__char%8)) 
241                         _decode64_sh__s="$(($_decode64_sh__s-8))" 
242                     done 
243                     _decode64_sh__v="0"; _decode64_sh__n="0" 
244                 fi 
245                 [ X"${_decode64_sh__args}" = X"${_decode64_sh__char}" ] &&\ 
246                     _decode64_sh__args='' || _decode64_sh__args="${_decode64_sh__args#?}" 
247             done 
248         } 
249         printf "%s\\n" "${@}" | _decode64_sh 
250     fi 
251 } # too hardcore for vim syntax`" 
252 #==================================================== Example ==== 
253 #string="$(_decode64 "${string}")" 
254 #[ -z "${string}" ] && printf "%s\\n" "fail, empty string" 
255 #================================================================= 
256 
374 _encode64() { #encode a base64 string 
375     [ ! -t 0 ] && set -- "${@}" "$(cat)" 
376     [ -z "${1}" ] && return 1 
377     if command -v "base64" >/dev/null 2>&1; then 
378         printf "%s\\n" "${@}" | base64 
379     elif command -v "openssl" >/dev/null 2>&1; then 
380         printf "%s\\n" "${@}" | openssl enc -base64 
381     else 
382         _encode64_sh() { #slow but quite portable 
383             [ ! -t 0 ] && set -- "${@}" "$(cat)" 
384             _od() { 
385                 if command -v "od" >/dev/null 2>&1; then 
386                     od -v -t x1 
387                 else 
388                     [ ! -t 0 ] && set -- "${@}" "$(cat)" 
389                     _od__O="0"; _od__W="16"; _od__args="$@" 
390                     while [ "${_od__args}" ]; do #process char by char 
391                         _od__char="${_od__args%${_od__args#?}}" 
392                         [ "$(($_od__O%$_od__W))" -eq "0" ] && printf '%07o' "${_od__O}" 
393                         printf ' %02x' "'${_od__char}" 
394                         _od__O="$(($_od__O+1))" 
395                         [ "$(($_od__O%$_od__W))" -eq "0" ] && printf "\\n" 
396                         [ X"${_od__args}" = X"${_od__char}" ] &&\ 
397                             _od__args='' || _od__args="${_od__args#?}" 
398                     done 
399                     printf " 0a\\n" 
400                 fi 
401             } 
402              __0='A';  __1='B';  __2='C';  __3='D';  __4='E';  __5='F';  __6='G';  __7='H';  __8='I';  __9='J'; 
403             __10='K'; __11='L'; __12='M'; __13='N'; __14='O'; __15='P'; __16='Q'; __17='R'; __18='S'; __19='T'; 
404             __20='U'; __21='V'; __22='W'; __23='X'; __24='Y'; __25='Z'; __26='a'; __27='b'; __28='c'; __29='d'; 
405             __30='e'; __31='f'; __32='g'; __33='h'; __34='i'; __35='j'; __36='k'; __37='l'; __38='m'; __39='n'; 
406             __40='o'; __41='p'; __42='q'; __43='r'; __44='s'; __45='t'; __46='u'; __47='v'; __48='w'; __49='x'; 
407             __50='y'; __51='z'; __52='0'; __53='1'; __54='2'; __55='3'; __56='4'; __57='5'; __58='6'; __59='7'; 
408             __60='8'; __61='9'; __62='+'; __63='/'; 
409             printf "%s\\n" "${@}" | _od | { 
410                 _encode64_sh__v="0"; _encode64_sh__w="0"; _encode64_sh__s="16" 
411                 while read _encode64_sh__line; do 
412                     for _encode64_sh__word in ${_encode64_sh__line}; do 
413                         [ X"${#_encode64_sh__word}" = X"7" ] && continue 
414                         _encode64_sh__v="$((16#${_encode64_sh__word} << ${_encode64_sh__s} | ${_encode64_sh__v}))" 
415                         _encode64_sh__s="$((${_encode64_sh__s}-8))" 
416                         [ "${_encode64_sh__s}" -lt "0" ] || continue 
417                         _encode64_sh__s="18"; while [ "${_encode64_sh__s}" -ge "0" ]; do 
418                             case "$((${_encode64_sh__v} >> ${_encode64_sh__s} & 63))" in 
419                              0) printf "%s"  "${__0}" ;;  1) printf "%s"  "${__1}" ;;  2) printf "%s"  "${__2}" ;; 
420                              3) printf "%s"  "${__3}" ;;  4) printf "%s"  "${__4}" ;;  5) printf "%s"  "${__5}" ;; 
421                              6) printf "%s"  "${__6}" ;;  7) printf "%s"  "${__7}" ;;  8) printf "%s"  "${__8}" ;; 
422                              9) printf "%s"  "${__9}" ;; 10) printf "%s" "${__10}" ;; 11) printf "%s" "${__11}" ;; 
423                             12) printf "%s" "${__12}" ;; 13) printf "%s" "${__13}" ;; 14) printf "%s" "${__14}" ;; 
424                             15) printf "%s" "${__15}" ;; 16) printf "%s" "${__16}" ;; 17) printf "%s" "${__17}" ;; 
425                             18) printf "%s" "${__18}" ;; 19) printf "%s" "${__19}" ;; 20) printf "%s" "${__20}" ;; 
426                             21) printf "%s" "${__21}" ;; 22) printf "%s" "${__22}" ;; 23) printf "%s" "${__23}" ;; 
427                             24) printf "%s" "${__24}" ;; 25) printf "%s" "${__25}" ;; 26) printf "%s" "${__26}" ;; 
428                             27) printf "%s" "${__27}" ;; 28) printf "%s" "${__28}" ;; 29) printf "%s" "${__29}" ;; 
429                             30) printf "%s" "${__30}" ;; 31) printf "%s" "${__31}" ;; 32) printf "%s" "${__32}" ;; 
430                             33) printf "%s" "${__33}" ;; 34) printf "%s" "${__34}" ;; 35) printf "%s" "${__35}" ;; 
431                             36) printf "%s" "${__36}" ;; 37) printf "%s" "${__37}" ;; 38) printf "%s" "${__38}" ;; 
432                             39) printf "%s" "${__39}" ;; 40) printf "%s" "${__40}" ;; 41) printf "%s" "${__41}" ;; 
433                             42) printf "%s" "${__42}" ;; 43) printf "%s" "${__43}" ;; 44) printf "%s" "${__44}" ;; 
434                             45) printf "%s" "${__45}" ;; 46) printf "%s" "${__46}" ;; 47) printf "%s" "${__47}" ;; 
435                             48) printf "%s" "${__48}" ;; 49) printf "%s" "${__49}" ;; 50) printf "%s" "${__50}" ;; 
436                             51) printf "%s" "${__51}" ;; 52) printf "%s" "${__52}" ;; 53) printf "%s" "${__53}" ;; 
437                             54) printf "%s" "${__54}" ;; 55) printf "%s" "${__55}" ;; 56) printf "%s" "${__56}" ;; 
438                             57) printf "%s" "${__57}" ;; 58) printf "%s" "${__58}" ;; 59) printf "%s" "${__59}" ;; 
439                             60) printf "%s" "${__60}" ;; 61) printf "%s" "${__61}" ;; 62) printf "%s" "${__62}" ;; 
440                             63) printf "%s" "${__63}" ;; esac 
441                             #printf "%s" "${_encode64_sh__64:$((${_encode64_sh__v} >> ${_encode64_sh__s} & 63)):1}" 
442                             #printf "%s" "${_encode64_sh__64}" | cut -c$(($waa+1)) | tr -d '\n' 
443                             _encode64_sh__s="$((${_encode64_sh__s}-6))"; _encode64_sh__w="$((${_encode64_sh__w}+1))" 
444                             [ "${_encode64_sh__w}" -gt "75" ] && { printf "\\n"; _encode64_sh__w="0"; } 
445                         done 
446                     _encode64_sh__v="0"; _encode64_sh__s="16" 
447                     done 
448                 done 
449 
 
450                 case "${_encode64_sh__s}" in 
451                     8) _encode64_sh__n="11" ;; 
452                     0) _encode64_sh__n="5"  ;; 
453                     *) _encode64_sh__n="0"  ;; 
454                 esac 
455 
 
456                 [ X"${_encode64_sh__n}" = X"0" ] || { 
457                     _encode64_sh__s="18"; while [ "${_encode64_sh__s}" -gt "${_encode64_sh__n}" ]; do 
458                         case "$((${_encode64_sh__v} >> ${_encode64_sh__s} & 63))" in 
459                          0) printf "%s"  "${__0}" ;;  1) printf "%s"  "${__1}" ;;  2) printf "%s"  "${__2}" ;; 
460                          3) printf "%s"  "${__3}" ;;  4) printf "%s"  "${__4}" ;;  5) printf "%s"  "${__5}" ;; 
461                          6) printf "%s"  "${__6}" ;;  7) printf "%s"  "${__7}" ;;  8) printf "%s"  "${__8}" ;; 
462                          9) printf "%s"  "${__9}" ;; 10) printf "%s" "${__10}" ;; 11) printf "%s" "${__11}" ;; 
463                         12) printf "%s" "${__12}" ;; 13) printf "%s" "${__13}" ;; 14) printf "%s" "${__14}" ;; 
464                         15) printf "%s" "${__15}" ;; 16) printf "%s" "${__16}" ;; 17) printf "%s" "${__17}" ;; 
465                         18) printf "%s" "${__18}" ;; 19) printf "%s" "${__19}" ;; 20) printf "%s" "${__20}" ;; 
466                         21) printf "%s" "${__21}" ;; 22) printf "%s" "${__22}" ;; 23) printf "%s" "${__23}" ;; 
467                         24) printf "%s" "${__24}" ;; 25) printf "%s" "${__25}" ;; 26) printf "%s" "${__26}" ;; 
468                         27) printf "%s" "${__27}" ;; 28) printf "%s" "${__28}" ;; 29) printf "%s" "${__29}" ;; 
469                         30) printf "%s" "${__30}" ;; 31) printf "%s" "${__31}" ;; 32) printf "%s" "${__32}" ;; 
470                         33) printf "%s" "${__33}" ;; 34) printf "%s" "${__34}" ;; 35) printf "%s" "${__35}" ;; 
471                         36) printf "%s" "${__36}" ;; 37) printf "%s" "${__37}" ;; 38) printf "%s" "${__38}" ;; 
472                         39) printf "%s" "${__39}" ;; 40) printf "%s" "${__40}" ;; 41) printf "%s" "${__41}" ;; 
473                         42) printf "%s" "${__42}" ;; 43) printf "%s" "${__43}" ;; 44) printf "%s" "${__44}" ;; 
474                         45) printf "%s" "${__45}" ;; 46) printf "%s" "${__46}" ;; 47) printf "%s" "${__47}" ;; 
475                         48) printf "%s" "${__48}" ;; 49) printf "%s" "${__49}" ;; 50) printf "%s" "${__50}" ;; 
476                         51) printf "%s" "${__51}" ;; 52) printf "%s" "${__52}" ;; 53) printf "%s" "${__53}" ;; 
477                         54) printf "%s" "${__54}" ;; 55) printf "%s" "${__55}" ;; 56) printf "%s" "${__56}" ;; 
478                         57) printf "%s" "${__57}" ;; 58) printf "%s" "${__58}" ;; 59) printf "%s" "${__59}" ;; 
479                         60) printf "%s" "${__60}" ;; 61) printf "%s" "${__61}" ;; 62) printf "%s" "${__62}" ;; 
480                         63) printf "%s" "${__63}" ;; esac 
481                         #printf "%s" "${_encode64_sh__64:$((${_encode64_sh__v} >> ${_encode64_sh__s} & 63)):1}" 
482                         #printf "%s" "${_encode64_sh__64}" | cut -c$(($waa+1)) | tr -d '\n' 
483                         _encode64_sh__s="$((${_encode64_sh__s}-6))"; _encode64_sh__w="$((${_encode64_sh__w}+1))" 
484                         [ "${_encode64_sh__w}" -gt "75" ] && { printf "\\n"; _encode64_sh__w="0"; } 
485                     done 
486 
 
487                     _encode64_sh__s="$((${_encode64_sh__n}/5))"; while [ "${_encode64_sh__s}" -gt "0" ]; do 
488                         _encode64_sh__s="$((${_encode64_sh__s}-1))"; printf "=" 
489                     done 
490                 } 
491                 printf "\\n" 
492             } 
493         } 
494         printf "%s\\n" "${@}" | _encode64_sh 
495     fi 
496 } 
497 #==================================================== Example ==== 
498 #string="$(_encode64 "${string}")" 
499 #================================================================= 
500 
981 _shuf() { #shuffle input 
982     awk 'BEGIN{srand()}{print rand()"\t"$0}' "${@}" | sort | cut -f2- 
983 } 
984 #==================================================== Example ==== 
985 #printf "%s" "1,2,3,4,5" | tr ',' '\n' | _shuf | tr '\n' ',' 
986 #================================================================= 
987 
 
988 _str2octal() { #convert a string to octal 
989     [ -z "${1}" ] && return 1 
990     printf "%s" "${@}" | od -v -A n -t o1 | \ 
991         sed "s:^ ::" | tr -d "\n" 
992 } 
993 #==================================================== Example ==== 
994 #hello="hello" 
995 #hello="$(_str2octal "${hello}")" 
996 #printf "%s\\n" "${hello}"   #prints "150 145 154 154 157" 
997 #================================================================= 
998 
 
999 _str2octal_escaped() { #convert a string to escaped octal 
1000     [ -z "${1}" ] && return 1 
1001     printf "%s" "${@}" | od -v -A n -t o1 | \ 
1002         sed "s/ *\([0-9]*\) */\\\\\1/g" | tr -d "\n" 
1003 } 
1004 #==================================================== Example ==== 
1005 #hello="hello" 
1006 #hello="$(_str2octal "${hello}")" 
1007 #printf "%s\\n" "${hello}"   #prints "\150\145\154\154\157" 
1008 #================================================================= 
1009 
 
1010 _str2lower() { #convert a string to lower string 
1011     [ -z "${1}" ] && return 1 
1012     printf "%s\\n" "${@}" | \ 
1013     tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' 
1014     # tr '[:upper:]' '[:lower:]' 
1015 } 
1016 #==================================================== Example ==== 
1017 #hello="HELLO WORLD" 
1018 #hello="$(_str2lower "${hello}")" 
1019 #printf "%s\\n" "${hello}"   #prints "hello world" 
1020 #================================================================= 
1021 
 
1022 _str2upper() { #convert a string to lower string 
1023     [ -z "${1}" ] && return 1 
1024     printf "%s\\n" "${@}" | \ 
1025     tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 
1026     # tr '[:upper:]' '[:lower:]' 
1027 } 
1028 #==================================================== Example ==== 
1029 #hello="hello world" 
1030 #hello="$(_str2upper "${hello}")" 
1031 #printf "%s\\n" "${hello}"   #prints "HELLO WORLD" 
1032 #================================================================= 
1033 
 
1034 _strdiff() { #prints the diff of two strings 
1035     [ -z "${1}" ] && return 1 
1036     [ -z "${2}" ] && return 1 
1037 
 
1038     mkfifo "${$}".fifo1 && mkfifo "${$}".fifo2 
1039     if [ -e "${$}".fifo1 ] && [ -e "${$}".fifo2 ]; then 
1040         _strdiff__1st_string="$(printf "%s" "${1}" | sed 's: :\n:g')" 
1041         _strdiff__2nd_string="$(printf "%s" "${2}" | sed 's: :\n:g')" 
1042         printf "%s\\n" "${_strdiff__1st_string}" > "${$}".fifo1 & 
1043         printf "%s\\n" "${_strdiff__2nd_string}" > "${$}".fifo2 & 
1044         _strdiff__diff="$(awk 'NR == FNR { A[$0]=1; next } !A[$0]' "${$}".fifo1 "${$}".fifo2)" 
1045         rm -rf "${$}".fifo1; rm -rf "${$}".fifo2 
1046         printf "%s\\n" "${_strdiff__diff}" 
1047     else 
1048         return 1 
1049     fi 
1050 } 
1051 #==================================================== Example ==== 
1052 #hello="hello world" 
1053 #world="world" 
1054 #diff="$(_strdiff "${world}" "${hello}")" 
1055 #printf "%s\\n"  "${diff}"   #prints "hello" 
1056 #================================================================= 
1057 
 
1058 _strduplicates() { #print duplicated strings, return 1 on failure 
1059     [ -z "${1}" ] && return 1 
1060     [ -z "${2}" ] && return 1 
1061     printf "%s\\n" $@ | awk 'x[$0]++' 
1062 } 
1063 #==================================================== Example ==== 
1064 #hello="hello world" 
1065 #bye="bye world" 
1066 #world=$(_strduplicates "${hello}" "${bye}") 
1067 #printf "%s\\n"  "${world}"   #prints "world" 
1068 #================================================================= 
1069 
 
1070 _strlen() { #print the length of a string, return 1 on failure 
1071     [ -z "${1}" ] && return 1 
1072     printf "%s\\n" "${#1}" 
1073 } 
1074 #==================================================== Example ==== 
1075 #_strlen "hello world!" #returns "12" 
1076 #================================================================= 
1077 
 
1078 _strreplace() { #replace param in string, return 1 on failure 
1079    #http://www.unix.com/shell-programming-and-scripting/124160-replace-word-string.html 
1080   _strreplace__orig="${1}" 
1081   [ -n "${3}" ] || return 1 #nothing to search for: error 
1082   _strreplace__srch="${2}"  #pattern to replace 
1083   _strreplace__rep="${3}"   #replacement string 
1084   case "${_strreplace__orig}" in 
1085     *"${_strreplace__srch}"*) #if pattern exists in the string 
1086        _strreplace__sr1="${_strreplace__orig%%$_strreplace__srch*}" #take the string preceding the first match 
1087        _strreplace__sr2="${_strreplace__orig#*$_strreplace__srch}"  #and the string following the first match 
1088        _strreplace__orig="${_strreplace__sr1}${_strreplace__rep}${_strreplace__sr2}" #and sandwich the replacement string between them 
1089        ;; 
1090   esac 
1091   printf "%s" "${_strreplace__orig}" 
1092 } 
1093 #==================================================== Example ==== 
1094 #hello="hello world" 
1095 #bye="$(_strreplace "${hello}" "hello" "bye")" 
1096 #printf "%s\\n" "${bye}"   #prints "bye world" 
1097 #================================================================= 
1098 
 
1099 _strreplace2() { #replace param in string, return 1 on failure 
1100     [ -z "${1}" ] && return 1 
1101     [ -z "${2}" ] && return 1 
1102     [ -z "${3}" ] && return 1 
1103     _strreplace2__replace=$(printf "%s" "${1}" | sed -e "s:${2}:${3}:g") 
1104     printf "%s" "${_strreplace2__replace}" 
1105 } 
1106 #==================================================== Example ==== 
1107 #hello="hello world" 
1108 #bye="$(_strreplace2 "${hello}" "hello" "bye")" 
1109 #printf "%s\\n" "${bye}"   #prints "bye world" 
1110 #================================================================= 
1111 
 
1112 _strunique() { #print unique strings, return 1 on failure 
1113     [ -z "${1}" ] && return 1 
1114     [ -z "${2}" ] && return 1 
1115     _strunique__retval="$(printf "%s\\n" $@ | \ 
1116         awk '!($0 in x) {x[$0];print}')" #faster 
1117         #printf "%s\\n" $@ | awk '!x[$0]++' 
1118     _strunique__retval="$(printf "%s" "${_strunique__retval}" | \ 
1119         tr '\n' ' ')" 
1120     printf "%s\\n" "${_strunique__retval}" 
1121 } 
1122 #==================================================== Example ==== 
1123 #hello="hello world" 
1124 #bye="bye world" 
1125 #world="$(_strunique "${hello}" "${bye}")" 
1126 #printf "%s\\n"  "${world}"   #prints "hello world bye" 
1127 #================================================================= 
1128 
 
1129 _subchar() { #print n character in string 
1130     [ -z "${1}" ] && return 1 
1131     [ -z "${2}" ] && return 1 
1132 
 
1133     if [ "${2}" -lt "0" ]; then 
1134         _subchar__pos="$((${#1} + ${2}))" 
1135     else 
1136         _subchar__pos="${2}" 
1137     fi 
1138 
 
1139     [ "${_subchar__pos}" -ge "${#1}" ] && return 1 
1140     [ "${_subchar__pos}" -lt "0" ]     && return 1 
1141 
 
1142     _subchar__string="${1}" 
1143 
 
1144     i="0"; while [ "${i}" -le "${_subchar__pos}" ]; do 
1145         _subchar__char="${_subchar__string#?}" 
1146         _subchar__char="${_subchar__string%$_subchar__char}" 
1147         i="$(($i+1))" 
1148         _subchar__string="${_subchar__string#?}" 
1149     done 
1150     #_subchar__retval="${_subchar__char}" 
1151     printf "%s\\n" "${_subchar__char}" 
1152 } 
1153 
 
1154 _subchar2() { #print n character in string 
1155     #faster but unsecure alternative 
1156     _subchar__string="${1}" 
1157     i="0"; while [ "${i}" -le "${2}" ]; do 
1158         _subchar__char="${_subchar__string#?}" 
1159         _subchar__char="${_subchar__string%$_subchar__char}" 
1160         i="$(($i+1))" 
1161         _subchar__string="${_subchar__string#?}" 
1162     done 
1163     #_subchar__retval="${_subchar__char}" 
1164     printf "%s\\n" "${_subchar__char}" 
1165 } 
1166 
 
1167 _substr() { #print a substring 
1168     [ -z "${1}" ] && return 1 
1169     [ -z "${2}" ] && return 1 
1170 
 
1171     if [ "${2}" -lt "0" ]; then 
1172         _substr__start="$((${#1} + ${2}))" 
1173     else 
1174         _substr__start="${2}" 
1175     fi 
1176 
 
1177     if [ -z "${3}" ]; then 
1178         _substr__len="${#1}" 
1179     else 
1180         if [ "${3}" -lt "0" ]; then 
1181             _substr__len="$((${#1} + ${3}))" 
1182         else 
1183             _substr__len="$((${_substr__start} + ${3}))" 
1184         fi 
1185     fi 
1186 
 
1187     _substr__start="$((${_substr__start} + 1))" 
1188 
 
1189     [ "${_substr__start}" -lt "0" ] && return 1 
1190     [ "${_substr__start}" -gt "${_substr__len}" ] && return 1 
1191 
 
1192     printf "%s\\n" "${1}" | cut -c"${_substr__start}"-"${_substr__len}" 
1193 } 
1194 #==================================================== Example ==== 
1195 #_substr "abcdef" 0 4 #print "abcd" 
1196 #================================================================= 
1197 
 
1263 _validip4() { 
1264     #return 0 if parameter is a valid ip4 address, non-zero otherwise 
1265     #https://groups.google.com/forum/#!original/comp.unix.shell/NDu-kAL5cHs/7Zpc6Q2Hu5YJ 
1266     [ -z "${1}" ] && return 1 
1267 
 
1268     case "${*}" in 
1269         ""|*[!0-9.]*|*[!0-9]) return 1 ;; 
1270     esac 
1271 
 
1272     OLDIFS="${IFS}" 
1273     IFS="." 
1274     set -- $@ 
1275     IFS="${OLDIFS}" 
1276 
 
1277     [ "${#}" -eq "4" ] && 
1278         [ "${1:-666}" -le "255" ] && [ "${2:-666}" -le "255" ] && 
1279         [ "${3:-666}" -le "255" ] && [ "${4:-666}" -le "254" ] 
1280 } 
1281 #===================================================== Example ==== 
1282 #if ! _validip4 "${ip}"; then 
1283     #printf "%s\\n" "not valid ip: ${ip}" 
1284 #fi 
1285 #================================================================= 
1286 
 
1287 _validmail() { #verify if an email is valid, return 1 on failure 
1288     case "${1}" in 
1289         *@*.*) return 0 ;; 
1290          *|"") return 1 ;; 
1291     esac 
1292 } 
1293 #===================================================== Example ==== 
1294 #if ! _validmail "${address}"; then 
1295     #printf "%s\\n" "not valid email address: ${address}" 
1296 #fi 
1297 #================================================================= 
1298 
 
1299 _validnetinterface() { 
1300     #check if parameter is a valid network interface 
1301     #return 0 if sucess, 0 otherwise 
1302     [ -z "${1}" ] && return 1 
1303     ip addr show | grep "${1}": >/dev/null && return 0 
1304 } 
1305 #===================================================== Example ==== 
1306 #if ! _validnetinterface "${interface}"; then 
1307     #printf "%s\\n" "not valid interface ${interface}" 
1308 #fi 
1309 #================================================================= 
1310 
981 _shuf() { #shuffle input 
982     awk 'BEGIN{srand()}{print rand()"\t"$0}' "${@}" | sort | cut -f2- 
983 } 
984 #==================================================== Example ==== 
985 #printf "%s" "1,2,3,4,5" | tr ',' '\n' | _shuf | tr '\n' ',' 
986 #================================================================= 
987