Search code examples
bashif-statementeval

How can I test a command before a pipe, 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

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"

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 successful 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.


Solution

  • Try with set -o pipefail.

    Check the manual: The Set Builtin

    Usually, bash returns the exit code of the last command of a pipe group, so your Debug command was the one that was checked. With that setting, bash returns the exit status of the last (rightmost) command to exit with a non-zero status. If your command fails, that is the status that get propagated.