Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a progress bar to a shell script?

Tags:

bash

shell

zsh

When scripting in bash or any other shell in *NIX, while running a command that will take more than a few seconds, a progress bar is needed.

For example, copying a big file, opening a big tar file.

What ways do you recommend to add progress bars to shell scripts?

like image 482
Tom Feiner Avatar asked Oct 26 '08 14:10

Tom Feiner


1 Answers

You can implement this by overwriting a line. Use \r to go back to the beginning of the line without writing \n to the terminal.

Write \n when you're done to advance the line.

Use echo -ne to:

  1. not print \n and
  2. to recognize escape sequences like \r.

Here's a demo:

echo -ne '#####                     (33%)\r' sleep 1 echo -ne '#############             (66%)\r' sleep 1 echo -ne '#######################   (100%)\r' echo -ne '\n' 

In a comment below, puk mentions this "fails" if you start with a long line and then want to write a short line: In this case, you'll need to overwrite the length of the long line (e.g., with spaces).

like image 159
Mitch Haile Avatar answered Oct 05 '22 03:10

Mitch Haile