刷新在bash中运行程序时的输出

huangapple go评论55阅读模式
英文:

Flushing output while program runs from bash

问题

我对Bash脚本不太熟悉,所以请耐心等待。

我有一个类似这样的小脚本:

readarray -t lines < <($COMMAND)
for line in "${lines[@]}"; do 
    echo $line
    theLines+="$line\n"
done

$COMMAND尚未完成时,STDOUT上肯定不会有任何输出。

它可以是ls -launzip或其他任何命令。

如何实时打印命令的输出?

英文:

I am not so familiar with bash scripts, so please be patient with me.

I have a little script like this:

readarray -t lines &lt; &lt;($COMMAND)
for line in &quot;${lines[@]}&quot;; do 
    echo $line
	theLines+=&quot;$line\n&quot;
done

Surely nothing will be on STDOUT while $COMMAND not finished.

It could be an ls -la, unzip whatever.

How can I print the output of command real time?

答案1

得分: 1

不要首先将输出存储在数组中。让循环直接从命令中读取。readarray 必须等到读取完所有输出才能完成。

while read -r line; do
    echo "$line"
    theLines+="$line"$'\n'
done < <($COMMAND)

如果你真的想要将其存储在数组中,你可以在循环中向数组添加内容。

while read -r line; do
    echo "$line"
    theLines+="$line"$'\n'
    lines+=("$line")
done < <($COMMAND)

还请注意,你必须使用 $'\n' 来获得 theLines 中的换行符。转义序列不会在双引号内展开。

英文:

Don't store the output in an array first. Have the loop read from the command itself. readarray can't finish until it had read all the output.

while read -r line; do
    echo &quot;$line&quot;
    theLines+=&quot;$line&quot;$&#39;\n&#39;
done &lt; &lt;($COMMAND)

If you really want it in an array, you can add to the array in the loop.

while read -r line; do
    echo &quot;$line&quot;
    theLines+=&quot;$line&quot;$&#39;\n&#39;
    lines+=(&quot;$line&quot;)
done &lt; &lt;($COMMAND)

Note also that you have to use $&#39;\n&#39; to get a newline in theLines. Escape sequences aren't expanded inside double quotes.

huangapple
  • 本文由 发表于 2023年6月26日 07:12:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76552745.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定