How to add a progress bar to a shell script?

后端 未结 30 2217
情歌与酒
情歌与酒 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:41

    It may be achieved in a pretty simple way:

    • iterate from 0 to 100 with for loop
    • sleep every step for 25ms (0.25 second)
    • append to the $bar variable another = sign to make the progress bar wider
    • echo progress bar and percentage (\r cleans line and returns to the beginning of the line; -ne makes echo doesn't add newline at the end and parses \r special character)
    function progress {
        bar=''
        for (( x=0; x <= 100; x++ )); do
            sleep 0.25
            bar="${bar}="
            echo -ne "$bar ${x}%\r"
        done
        echo -e "\n"
    }
    
    $ progress
    > ========== 10% # here: after 2.5 seconds
    
    $ progress
    > ============================== 30% # here: after 7.5 seconds
    

    COLORED PROGRESS BAR

    function progress {
        bar=''
        for (( x=0; x <= 100; x++ )); do
            sleep 0.05
            bar="${bar} "
    
            echo -ne "\r"
            echo -ne "\e[43m$bar\e[0m"
    
            local left="$(( 100 - $x ))"
            printf " %${left}s"
            echo -n "${x}%"
        done
        echo -e "\n"
    }
    

    To make a progress bar colorful, you can use formatting escape sequence - here the progress bar is yellow: \e[43m, then we reset custom settings with \e[0m, otherwise it would affect further input even when the progress bar is done.

提交回复
热议问题