zlovelady
zlovelady

Reputation: 4097

Simple console graphics, GUI or interface from a shell script?

I would like to spruce up the output of a Bash shell script by doing some simple, ncurses-like console displays.

For instance, I would like to show a percentage value increasing as some activity completes. I can do this by outputting each percent value on a new line, for example,

0%
1%
2%
... etc. ...

But I would prefer to have the text update in place (that is, the script only writes one line of output to show the percent, and then the percent value displayed on that line changes). I know I could use a different scripting language and ncurses, but is there a Bash solution that doesn't incur too much pain. Preferably, I'd like something with wide support across various Unix'es.

Upvotes: 2

Views: 3556

Answers (3)

geekosaur
geekosaur

Reputation: 61439

For full generality and portability, this would be the dialog package. The basic ncurses build is highly portable; there is also a Gtk+ GUI version called gdialog. You then have the option not only of what you described, but also an actual progress bar widget.

On the simpler side, simply outputting \r (use the printf utility, or on older commercial Unixes one of echo -n ...^M or echo ... \r\c) will let you overwrite a line.

Upvotes: 2

Hyperboreus
Hyperboreus

Reputation: 32439

Use ANSI escape codes for using or coloring your cursor.

Here a short example in python (run it with the -u flag for unbuffered because else you wouldn't see the updating):

#!/usr/bin/env python

import time
import sys

for i in range (10):
    sys.stdout.write ('%d\x1b[1D' % i)
    time.sleep (1)

CSInD ('\x1b[1D') moves the cursor n positions to the left. And if you want a colored cursor, just print e.g. '\x1b[1;31m'. Works on almost all shells.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799082

Outputting \r will return the cursor to the first column so that you can write over the text already in place. If you need more sophisticated motion than that, tput with the various cu* capabilities will allow you to move and place the cursor as desired.

Upvotes: 2

Related Questions