bashshellprogress-barzsh

How to add a progress bar to a shell script?


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?


Solution

  • 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).