Tuesday, December 17, 2013

[BASH SCRIPTING] Get exit status on the piped process

#!/bin/bash

function logging() {
  while read line; do
    echo "{$(date +'%Y-%m-%d %H:%M:%S')} $line"
  done
}

function stdintoexitstatus() {
  read exitstatus
  return $exitstatus
}

cmds=(
    "cal"
    "cal lkjhsd"
)
for i in $(seq 0 $((${#cmds[@]}-1)))
do
    echo "--------------------------------------------------------"
    echo "[COMMAND] ${cmds[$i]}"
    echo "--------------------------------------------------------"
   ((((eval ${cmds[$i]} 2>&1; echo $? >&3) | logging >&4) 3>&1) | stdintoexitstatus) 4>&1
    echo "Exit Status[$?]"
    echo
done

COMMAND:  eval ${cmds[$i]} 2>&1
The output and the error messages of the eval are redirected to stdout

COMMAND:   echo $? >&3
The status of the eval is stored in the file descriptor 3

COMMAND:   | logging >&4
The (output/error)stdout from eval is piped to logging function where we do logging
and the output of the logging function is stored in file descriptor 4

COMMAND:   3>&1 | stdintoexitstatus
Get the status of eval from file descriptor 3 and update $?

COMMAND:   4>&1
Get the output of the logging function from file descriptor 4 and redirect them to stdout

Reference: http://unix.stackexchange.com/questions/14270/get-exit-status-of-process-thats-piped-to-another