我在Linux Mint中运行一个shell脚本,它调用一些进程花费几分钟的时间。 对于每一个过程中,我想回应类似这样的消息:显示运行bash脚本的每秒运行时间
echo "Cleaning temporary files... X seconds."
myprocess
,其中X是当前经过的时间,我想它改变每一秒,但不能打印新的生产线。
有没有很好的方法来做到这一点?我只找到了打印总时间的方法,但不是运行流程的时间。
我在Linux Mint中运行一个shell脚本,它调用一些进程花费几分钟的时间。 对于每一个过程中,我想回应类似这样的消息:显示运行bash脚本的每秒运行时间
echo "Cleaning temporary files... X seconds."
myprocess
,其中X是当前经过的时间,我想它改变每一秒,但不能打印新的生产线。
有没有很好的方法来做到这一点?我只找到了打印总时间的方法,但不是运行流程的时间。
使用此在脚本的开始,这造成其在后台运行,并不断更新状态的子进程。
file=$(mktemp)
progress() {
pc=0;
while [ -e $file ]
do
echo -ne "$pc sec\033[0K\r"
sleep 1
((pc++))
done
}
progress &
#Do all the necessary staff
#now when everything is done
rm -f $file
你可以用时间运行命令:
time <command>
,然后用sed/awk来exctract经过的时间。
您必须在后台运行进程&
,否则脚本的其余部分将一直等到完成。使用backspaces覆盖您的当前行,所以请确保您不使用换行符。
所以,做你想做的:
myproc &
myPid=$! # save process id
tmp=""
while true; do
if kill -0 "$myPid"; then # if the process accepts a signal, keep waiting
for i in {0..${#tmp}..1}; do
printf "%b" "\b" # print backspaces until we have cleared the previous line
done
tmp=$(printf "Cleaning temp files... %t seconds.")
printf "%s" "$tmp"
else
break # drop out of the while loop
fi
sleep 1
done
这已经很不错了。为什么不使用回车,\ r呢?为了说明不同的文本长度,你可以打印一些额外的空格。它更干净。你也忘了睡在你的循环中。 – ypnos
@ypnos我保持我的字符串,所以我可以得到所有的长度和退格,不需要额外的空格。我相信'\ r'与'\ n'有相同的问题,但是如果他感兴趣,他可以测试它。感谢您注意失踪的睡眠。 –
这里是一个办法,让awk打印STDERR每秒。 你应该只需要添加:
环部分(不终止测试......如此“无限循环”,直到CTRL-C)是:
ping 127.0.0.1 | awk '
BEGIN{cmd="date +%s"; cmd|getline startup ; close (cmd) }
/bytes from/ { cmd | getline D ; close (cmd) ;
print D-startup | "cat >&2" }'
现在你只需要使用的“printf”和ANSI转义序列,不换行打印,H AVE的ANSI-逃生回去,直到号码的开头,并刷新通过调用系统输出(所有描述符):
ping 127.0.0.1 | awk -v getback4char="$(printf '\033[4D')" '
BEGIN{cmd="date +%s"; cmd|getline startup ; close (cmd) ; printf "Elapsed time: ";}
/bytes from/ { cmd | getline D ; close (cmd) ;
printf "%4d%s" ,(D-startup) , getback4char | "cat >&2"
system("") }'
注:这是所有版本的awk,我知道的,甚至是古老兼容(也就是说,不是gawk/nawk,而是古老的awk。)
对于printf上的错字感到抱歉,现在它再次运行(并显示“已用时间”) –
时间很重要,还是仅仅是某种进步? – mouviciel
@mouviciel它会帮助我控制每个进程运行多少时间。 – rafa
看看这个答案:[如何创建一个秒表Bash脚本来不断显示已用时间?](http://stackoverflow.com/a/10244193/98117)。 – hammar