【问题标题】:Bash: run command for a certain amount of time and get its outputBash:运行命令一段时间并获取其输出
【发布时间】:2017-07-29 16:04:00
【问题描述】:

所以我正在尝试运行一个脚本来捕获命令的输出:

 echo 'password' | sudo -S strace -p14750 -s9999 -e write

大约 5 秒,然后将输出存储到变量中。 我该怎么做?

完整脚本:

    appium_pid_output=$(echo 'password' | sudo -S strace -p$appium_device_pid -s9999 -e write)
    echo 'captured output of node '$appium_pid_output

    if [[ $appium_pid_output == *POST* ]]; then
        echo "device [ " + $device + " ] is currently in use"
        return 1
    fi

【问题讨论】:

  • 很高兴有一些反馈。我的回答有问题吗?

标签: bash command-line command timeout strace


【解决方案1】:

使用timeout 命令。

var="$(timeout 5 whateverProducesTheOutput)"

一个缺点是超时不适用于复杂的命令。解决此问题的最简单方法是编写一个函数并在超时的情况下执行该函数(请参阅this answer)。

foo() {
    whateverProducesTheOutput
}
export -f foo
var="$(timeout 5 bash -c foo)"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-19
    • 2013-01-01
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    • 2018-04-17
    相关资源
    最近更新 更多