首页 > bash 中的进度条动画是怎么实现的?

bash 中的进度条动画是怎么实现的?

诸如下面这种:

[ #################### ]     99%
[ #####                ]     30%
[ ##########           ]     60%

还有一种是 npm install 会出现的,是几根斜杠不断变化造成滚动的效果,请问这些都是怎么实现的?

\  5%
|  6%
/  7%
-  8%

恩, 应该是下面这样的

echo -en '[ #                    ]     05%\r'
echo -en '[ ###################  ]     95%'

其中, \r是关键. -en参数也是不可少的.


from arch linux pacman:callback.c

/* refactored from cb_trans_progress */
static void fill_progress(const int bar_percent, const int disp_percent,
    const int proglen)
{
/* 8 = 1 space + 1 [ + 1 ] + 5 for percent */
const int hashlen = proglen - 8;
const int hash = bar_percent * hashlen / 100;
static int lasthash = 0, mouth = 0;
int i;

if(bar_percent == 0) {
    lasthash = 0;
    mouth = 0;
}

if(hashlen > 0) {
    fputs(" [", stdout);
    for(i = hashlen; i > 0; --i) {
        /* if special progress bar enabled */
        if(config->chomp) {
            if(i > hashlen - hash) {
                putchar('-');
            } else if(i == hashlen - hash) {
                if(lasthash == hash) {
                    if(mouth) {
                        fputs("\033[1;33mC\033[m", stdout);
                    } else {
                        fputs("\033[1;33mc\033[m", stdout);
                    }
                } else {
                    lasthash = hash;
                    mouth = mouth == 1 ? 0 : 1;
                    if(mouth) {
                        fputs("\033[1;33mC\033[m", stdout);
                    } else {
                        fputs("\033[1;33mc\033[m", stdout);
                    }
                }
            } else if(i % 3 == 0) {
                fputs("\033[0;37mo\033[m", stdout);
            } else {
                fputs("\033[0;37m \033[m", stdout);
            }
        } /* else regular progress bar */
        else if(i > hashlen - hash) {
            putchar('#');
        } else {
            putchar('-');
        }
    }
    putchar(']');
}
/* print display percent after progress bar */
/* 5 = 1 space + 3 digits + 1 % */
if(proglen >= 5) {
    printf(" %3d%%", disp_percent);
}

if(bar_percent == 100) {
    putchar('\n');
} else {
    putchar('\r');
}
fflush(stdout);

}

【热门文章】
【热门文章】