1

I have written a common function to execute any given command and fetch stdout and stderr to a variable. However, command with pipe doesn't work properly.

I also tried with eval however, unable to redirect stdout/stderr to a variable

Here is my function

LOGFILE="mylog.txt"

Log() {
    msg=$2
    level=$1
    timestamp=`date "+[%F %T]"`
    echo ""
    echo "" >> $LOGFILE
    echo "$timestamp [$level] ==> $msg"
    echo ""
    echo "$timestamp [$level] ==> $msg" >> $LOGFILE
    echo "" >> $LOGFILE
}

RunCommand() {
    CMD=$1
    MSG1=`printf "Executing command \nCommand: $1"`

    OUTPUT=`$CMD 2>&1`
    ERRCODE=`echo $?`

    MSG2=`printf "\n\nOutput: \n%s" "${OUTPUT}"`
    MSG3=`printf "\n\nError Code: %s\n%s" "${ERRCODE}"`
    Log INFO "${MSG1}${MSG2}${MSG3}"
}

command="df -h | grep /$"
RunCommand "$command"

Output:

[2019-05-02 05:01:29] [INFO] ==> Executing command
Command: df -h | grep /$

Output:
df: '|': No such file or directory
df: grep: No such file or directory
df: '/$': No such file or directory

Error Code: 1

Other commands are working without any error. Executed script with another long command.

[2019-05-02 05:10:20] [INFO] ==> Executing command
Command: find /var/bundle/upgrade/ -type f -size +1b

Output:
/var/bundle/upgrade/upgrade.sh
/var/bundle/upgrade/run_task.py
/var/bundle/upgrade/lib/UpgradeTask.pyc
/var/bundle/upgrade/lib/Constants.pyc
/var/bundle/upgrade/lib/Constants.py
/var/bundle/upgrade/lib/UpgradeTask.py
/var/bundle/upgrade/util/FileSystem.pyc

Error Code: 0
2

2 Answers 2

1

check if below changes work for you

RunCommand() {
    CMD=$1
    MSG1=`printf "Executing command \nCommand: $1"`

    OUTPUT=$(eval "$CMD 2>&1")
    ERRCODE=`echo $?`

    MSG2=`printf "\n\nOutput: \n%s" "${OUTPUT}"`
    MSG3=`printf "\n\nError Code: %s\n%s" "${ERRCODE}"`
    Log INFO "${MSG1}${MSG2}${MSG3}"
}
Sign up to request clarification or add additional context in comments.

Comments

0

A small fix :-)

You forgot to add eval

LOGFILE="mylog.txt"

Log() {
    msg=$2
    level=$1
    timestamp=`date "+[%F %T]"`
    echo ""
    echo "" >> $LOGFILE
    echo "$timestamp [$level] ==> $msg"
    echo ""
    echo "$timestamp [$level] ==> $msg" >> $LOGFILE
    echo "" >> $LOGFILE
}

RunCommand() {
    CMD=$1
    MSG1=`printf "Executing command \nCommand: $1"`

    OUTPUT=`$CMD 2>&1`
    ERRCODE=`echo $?`

    MSG2=`printf "\n\nOutput: \n%s" "${OUTPUT}"`
    MSG3=`printf "\n\nError Code: %s\n%s" "${ERRCODE}"`
    Log INFO "${MSG1}${MSG2}${MSG3}"
}

command="df -h | grep /$"
eval RunCommand "$command"

Output on my machine:

/dev/sda3 152658276 92448632 52432648 64% /

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.