How to add a progress bar to a shell script?

后端 未结 30 2788
情歌与酒
情歌与酒 2020-11-22 05:48

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 b

30条回答
  •  爱一瞬间的悲伤
    2020-11-22 06:40

    I prefer to use dialog with the --gauge param. Is used very often in .deb package installations and other basic configuration stuff of many distros. So you don't need to reinvent the wheel... again

    Just put an int value from 1 to 100 @stdin. One basic and silly example:

    for a in {1..100}; do sleep .1s; echo $a| dialog --gauge "waiting" 7 30; done
    

    I have this /bin/Wait file (with chmod u+x perms) for cooking purposes :P

    #!/bin/bash
    INIT=`/bin/date +%s`
    NOW=$INIT
    FUTURE=`/bin/date -d "$1" +%s`
    [ $FUTURE -a $FUTURE -eq $FUTURE ] || exit
    DIFF=`echo "$FUTURE - $INIT"|bc -l`
    
    while [ $INIT -le $FUTURE -a $NOW -lt $FUTURE ]; do
        NOW=`/bin/date +%s`
        STEP=`echo "$NOW - $INIT"|bc -l`
        SLEFT=`echo "$FUTURE - $NOW"|bc -l`
        MLEFT=`echo "scale=2;$SLEFT/60"|bc -l`
        TEXT="$SLEFT seconds left ($MLEFT minutes)";
        TITLE="Waiting $1: $2"
        sleep 1s
        PTG=`echo "scale=0;$STEP * 100 / $DIFF"|bc -l`
        echo $PTG| dialog --title "$TITLE" --gauge "$TEXT" 7 72
    done
    
    if [ "$2" == "" ]; then msg="Espera terminada: $1";audio="Listo";
    else msg=$2;audio=$2;fi 
    
    /usr/bin/notify-send --icon=stock_appointment-reminder-excl "$msg"
    espeak -v spanish "$audio"
    

    So I can put:

    Wait "34 min" "warm up the oven"

    or

    Wait "dec 31" "happy new year"

提交回复
热议问题