2018-02-02

Subroutine/Procedure/Function that Reads from Standard Input (Pipe)

The procedure "pipe2dbg()" reads from the standard input (from a pipe), copies the input to the standard output and - if enabled - also to a debug log file.
# Enables/disables the debugging 
typeset -r C_DO_DBG="Y"

# Define the path of the debug log file
typeset -r C_DBG_FILE="/tmp/myDebugFile.log"

pipe2dbg () {
  if [[ -n "${C_DBG_FILE}" && "${C_DO_DBG}" == "Y" ]]; then
    while read line; do
      print - "${line}" | tee -a ${C_DBG_FILE}
    done
  else
    while read line; do
      print - "${line}"
    done
  fi
}

The procedure "pipe2stderr()" reads from the standard input (from a pipe), copies the input to the standard output and if one of the keywords "error|warning|sorry" are found, writes to the standard error output (see "1>&2") instead of standard output:
pipe2stderr () {
  typeset L_ERR_STR
  while read line; do
    L_ERR_STR="$(print - "${line}" | egrep -e 'error|warning|sorry')"
    if [[ -n "${L_ERR_STR}" ]]; then
      print - "E: ${L_ERR_STR}" 1>&2
    else
      print - "${line}"
    fi
  done
}


Usage examples in ksh/bash scripts.

Example 1
. . .
print - "Write this to the standard output and to the debug log file" | pipe2dbg
. . .

Example 2
Writing the output of Oracle sqlplus SQL statements to the standard output with the possibility to enable disable the debugging output to a debug log file:

. . .
sqlplus -SILENT /NOLOG <<EOSQL | pipe2dbg
  CONNECT <DbUser>/<Password>
  <SQL Statements>
EOSQL
. . .

No comments :

Post a Comment