I want to inplement a progress bar use C like tqdm in Python or apt-get in Ubuntu. But I have no idea.
My problem is how to make the progress bar always be at the bottom of the terminal, and the top normally outputs something else.
Like the apt-get program in Ubuntu is implemented in the following figure.
CodePudding user response:
If I understand you are simply trying to find only the progress bar within the apt or apt-get code, so you can make use of it later, then there is no guarantee that it is named Progress:, or that the prompt containing Progress: is even in the script you are searching. It is likely sourced from another file.
You can try opening the script in an editor like vim or kwrite or jot, etc. and looking within the script for where the meter is called and go from there. There is no telling whether it will be under scale, meter, percent, etc...
In the absence of finding anything, you can always use something simple. There are many available on the web. Example:
#!/bin/bash
## string of characters for meter (60 - good for 120 char width)
str='▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒'
tput civis # make cursor invisible
for i in `seq 1 100`; do # for 1 to 100, save cursor, restore, output, restore
printf "\033[s\033[u Progress: %s = %% \033[u" "${str:0:$(((i 1)/2))}" "$i"
sleep 0.1 # small delay
done
printf "\033[K" # clear to end-of-line
tput cnorm # restore cursor to normal
exit 0
CodePudding user response:
This isn't portable as it assumes the terminal has 24 lines. It might be useful as a framework for your project.
Only one parameter is passed to progress. That can be changed for your project.
An actual percentage calculation would be needed for your project. This uses a done
loop for display purposes.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define LINES 24
void showprogress ( int percent);
int main ( void) {
int textrow = 0;
printf ( "\033[2J"); // clear screen
printf ( "\033[1;1H"); // move to row 1 col 1
for ( int loop = 1; loop <= 100; loop) {
textrow = textrow < LINES - 1;
printf ( "\033[%d;1H", textrow); // move to textrow col 1
printf ( "task %d", loop);
for ( int done = 0; done <= 100; done = 5) {
showprogress ( done);
}
showprogress ( 100);
usleep ( 100000); // about 1/10 second
if ( 23 == textrow) {
printf ( "\033[%d;1H", LINES); // move to row LINES col 1
printf ( "\033[2K"); // erase line
printf ( "\n"); // scroll
}
}
return 0;
}
void showprogress ( int percent) {
printf ( "\033[%d;1H", LINES); // move to row LINES col 1
printf ( "=%% progress ", percent);
fflush ( stdout);
usleep ( 100000); // about 1/10 second
}