There are instances when writing a shell script that you want to write to the same line over and over. This is mainly used for progress meters that update the same screen position over and over. Most languages represent a carriage return without newline as the \r escape sequence. In shell, it's no different, but there is one small caveat. The echo command requires two arguments.
#!/bin/bash
# simplest progress meter
items=100000
for ((i=0; i<$items; i+=1)); do
echo -n -e "Processed $i/$items\r"
done
The -n argument to echo tells it to suppress the implicit newline that it usually includes. The -e argument tells it to respect escape sequences such as \r.
4 comments:
This works as well:
printf "Processed $i/$items\r"
Ah, the ubiquitious printf. Thanks for the tip!
\r is pretty nice detail :-)
Thanks
Just an fyi that without a sleep command after the echo my shell just hung. I'm using cygwin on XP though so on a real *nix system ymmv
Post a Comment