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