英文:
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 -la
,unzip
或其他任何命令。
如何实时打印命令的输出?
英文:
I am not so familiar with bash scripts, so please be patient with me.
I have a little script like this:
readarray -t lines < <($COMMAND)
for line in "${lines[@]}"; do
echo $line
theLines+="$line\n"
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 "$line"
theLines+="$line"$'\n'
done < <($COMMAND)
If you really want it in an array, you can add to the array in the loop.
while read -r line; do
echo "$line"
theLines+="$line"$'\n'
lines+=("$line")
done < <($COMMAND)
Note also that you have to use $'\n'
to get a newline in theLines
. Escape sequences aren't expanded inside double quotes.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论