#!/bin/bash proc stderr { echo @Argv > !2 } proc putd { stderr "$1=<$(!1)>" } proc exists { type @Argv >/dev/null !2 >/dev/null } proc test_grepq { var output = $[echo x | grep -q x] [[ $? == 0 ]] || return 1 [[ -z "$output" ]] || return 1 return 0 } proc test_greps { var output = $[echo x | grep -s x] [[ $? == 0 ]] || return 1 [[ -z "$output" ]] || return 1 return 0 } if test_grepq { proc matches { grep -q @Argv ;} } elif test_greps { proc matches { grep -s @Argv ;} } else { proc matches { grep @Argv !2 > !1 >/dev/null ;} } proc pluralize { if test -n $1 { # TODO: actually implement the inflector echo $(1)s } else { while read line { pluralize $line } } } #trim() { # trimmed="$1" # trimmed="${trimmed##*( )}" # trimmed="${trimmed%%*( )}" #} # for an explanation of this getc implementation, see # http://write.jayferd.us/blog/2011/01/12/bash-adventures-read-a-single-character-even-if-its-a-newline/ proc getc { env IFS= read -r -n1 -d '' @Argv } proc read_until { var glob = $1; shift var var = $1; shift var out = '' while getc ch { set out = ""$(out)$(ch)"" match $out { with *$glob setglobal FOUND = '1' export $var="$(out%$glob)" return 0 } } # we've hit an EOF if test -z $out { false } else { setglobal FOUND = '0' export $var="$out" true } } proc trim_l { var str = $(!1) set str = $(str##+([[:space:]])) export "$1"="$str" } proc trim_r { var str = $(!1) set str = $(str%%+([[:space:]])) export "$1"="$str" } proc trim { trim_l @Argv trim_r @Argv } # usage: db_safe my_var # will quote my_var for mysql. proc db_safe { var str = ""$(!1)."" # append a . so that bash doesn't chomp off newlines at the end var escaped_quote = '"\\''" set str = $[ echo $(str//\'/$escaped_quote) | while read line { echo -n "$line\\n"; }] # ^ escape ' escape \n - bash has trouble with this one. export "$1"="'$(str:0:${#str}-1)'" # enclose in single quotes, strip off the ., and export the variable } # escape ' with '\''. sorry everyone. proc bash_safe { var str = $(!1) # escape ' with (literally) '\'' - sorry everyone var escaped_quote = '"'\\'''" export "$1"="'$(str//\'/$escaped_quote)'" } proc join { var delim = $1 read line && echo -n $line while read line { echo -n $delim echo -n $line } }