notebox

Adding filter capabilities to any Bash function

If you have a bash function that can transform lines taken as arguments, the following trick can be used to give that function line-filter or file-filter capabilities, depending on how the function treats newlines.

mylinefunc() {
  __line_filter "$@" && return $?

  # transform a single line of input
  echo "${1-#}" "$*"
}

__line_filter() {
  [[ -n "$1" ]] && return 1
  while IFS= read -ra args; do
    "${FUNCNAME[1]}" "${args[@]}"
  done
}

Explanation:

If the function can handle line newlines, use __file_filter instead of __line_filter.

__file_filter() {
  [[ -n "$1" ]] && return 1
  "${FUNCNAME[1]}" "$(</dev/stdin)"
}

Related:

References:

Tags:

#literature-note #unix #io #bash #scripting #bash-tricks