Shell脚本函数使用管道执行命令,并将stdout和stderr重定向到变量

时间:2019-05-02 05:12:46

标签: bash shell

我编写了一个通用函数来执行任何给定命令,并将stdout和stderr提取到变量中。但是,使用管道命令无法正常工作。

我也尝试了 eval ,但是无法将stdout / stderr重定向到变量

这是我的职能

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"

输出:

[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

其他命令正常运行,没有任何错误。 用另一个长命令执行脚本。

[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 个答案:

答案 0 :(得分:1)

检查以下更改是否对您有用

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}"
}

答案 1 :(得分:0)

一个小修正:-)

您忘记添加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"

我的机器上的输出:

/dev/sda3 152658276 92448632 52432648 64% /