lundi 24 décembre 2018

How can I test a command, capture it's output and understand if the command ran successfully or not

I'm writting a script that will execute commands on different servers automatically and I am trying to log all it's content and output. I am having difficulties with redirections and command status output. Meaning was the command successfull and what is its output?

I have tried many directions such redirecting the command output to a function or file. I have tried a simple if statement. Both worked for there respected function. But when I am trying to combine both of them the script always return the command to be successfull. And to some level it is.

#!/bin/bash

LgFile="$(date +%s%N).log"

# Debug Switch
DEBUG=true

# Formatting variables

BLACK="\033[30m"
RED="\033[31m"
GREEN="\033[32m"
ORANGE="\033[33m"
BLUE="\033[34m"
PURPLE="\033[35m"
CYAN="\033[36m"
LIGHTGRAY="\033[37m"
RESET="\033[00m"
BOLD="\033[1m"
BLINK="\e[5m"
INVERTED="\e[7m"

PDATE(){
    printf "[$(date '+%Y-%m-%d %H:%M:%S')]"
}

# Log Types

INFO="[${CYAN}${BOLD}i${RESET}]"
OUTPUT="[${BOLD}!${RESET}]"
SUCCESS="[${GREEN}\xE2\x9C\x94${RESET}]"
ERROR="[${RED}\xE2\x9C\x98${RESET}]"

# Log Actions

CHECK="[CHECK ]"
START="[START ]"
RUN="[RUN   ]"
EMPT="[      ]"
OUT="[OUTPUT]"

function Debug(){
  if [ "$1" != "" ] && [ "$2" != "" ]; then
    case "$1" in
      info|i)
        TYPE=$INFO
        ;;
      success|s)
        TYPE=$SUCCESS
        ;;
      error|e)
        TYPE=$ERROR
        ;;
      output|o)
        TYPE=$OUTPUT
        ;;
    esac
    case "$2" in
      check|c|test|t)
        ACTION=$CHECK
        ;;
      start|s)
        ACTION=$START
        ;;
      run|r)
        ACTION=$RUN
        ;;
      empty|e)
        ACTION=$EMPT
        ;;
      output|o)
        ACTION=$OUT
        ;;
    esac
    while read DCMD; do
      printf "${TYPE}$(PDATE)${ACTION} ${DCMD}\n"
    done
  fi
}

function Executing(){
  if [ "$1" != "" ]; then
    if [ $DEBUG = "true" ]; then
      echo "$1" | Debug i s
      if $1 2>&1 | Debug o o;then
        echo "$1" | Debug s r
      else
        echo "$1" | Debug e r
      fi
    else
      eval $1
    fi
  fi
}

Executing "apt-get update"

Sorry for the long code, but to understand every part of it I had to provide a lot.

Also note that the system requires sudo to execute apt-get update. Thus the script should report & log an error. Right now tho, whenever I call the Executing function, the function returns a successfull execution. I am pretty sure it does because of the added pipe | debug o o that captures the output and formats it. Which I'll later redirect to a log file.

So I tested if apt-get update;then echo yes;else echo no; fi which worked in my terminal. But as soon as I pipe the output to the function debug, the if statement returns true.

I am not sure if I explained it enough so let me know if you need more information.

Aucun commentaire:

Enregistrer un commentaire