shell 进度条

2022/07/12 Linux Shell 共 831 字,约 3 分钟
电子技术小屋

函数

function _red() {
    printf '\033[1;31;31m%b\033[0m' "$1"
}

function _green() {
    printf '\033[1;31;32m%b\033[0m' "$1"
}

function _yellow() {
    printf '\033[1;31;33m%b\033[0m' "$1"
}

function _info() {
    _green "[Info] "
    printf -- "%s" "$1"
    printf "\n"
}

function _warn() {
    _yellow "[Warning] "
    printf -- "%s" "$1"
    printf "\n"
}

function _error() {
    _red "[Error] "
    printf -- "%s" "$1"
    printf "\n"
    exit 1
}

function _bar() {
    local num=0
    local str=''
    local max=100
    local postfix=('|' '/' '-' '\')
    local index
    while [ $num -le $max ]
    do
        ((index=num%4))
        printf "[%-50s %-2d%% %c]\r" "$str" "$num" "${postfix[$index]}"
        ((num++))
        # sleep "$( echo "scale=1; $1/$max" |bc )"
        sleep "$(awk 'BEGIN{ printf "%.2f\n",'"$1"'/'$max'}')"
        if ((num % 2 == 0)); then
            str+='#'
        fi
    done
    printf '\n'
}

function _bar_wait(){
    while [ "$(ps aux | awk '{print $2}' |grep -c $1)" != "0" ]
        do
        sleep 0.2
        done
    _info "Done!"
}

用法示例:

sleep 10 &    # 模拟用户后台任务
BG_PID=$!     # 记录后台任务PID号
_bar 10       # 预估10秒进度条
_bar_wait $BG_PID     # 等待用户进程退出

bar

文档信息

Search

    Table of Contents