Friday, February 14, 2014

Cool Bash Trick: Constantly updating a "status" line in bash script

Lots of times i'm dealing with repetitius data and i dont like that it can take up so much of my screen when i'm really only outputting something like "Portion 3 is done" and the only thing that updates is the number.

It's annoying to have a screen full of:
Portion 1 is done
Portion 2 is done
Portion 3 is done
Portion 4 is done
...


I'd like it if only one line is used to tell me the current done portion. Well, it turns out there is a way to do this with bash scripts.

It turns out there is "\r" which means carriage return. So if you output a carriage return WITHOUT a newline then you essentially clear that line of text.

A simple double for loop to visually see what i'm talking about:
for j in $(seq 1 10); do 
  for i in $(seq 1 20); do 
    printf "$i is part of $j \r"
    sleep .1
  done 
done