使用BASH显示进度(工作)指示器

时间:2012-09-19 15:50:18

标签: bash shell unix progress

使用仅限bash的脚本,如何提供bash进度指示器?

所以我可以运行命令表单bash,并且在执行该命令时让用户知道某些事情仍在发生。

11 个答案:

答案 0 :(得分:64)

在这个使用SCP的例子中,我正在演示如何获取进程id(pid),然后在该进程运行时执行某些操作。

这会显示一个简单的spinnng图标。

/usr/bin/scp me@website.com:file somewhere 2>/dev/null &
pid=$! # Process Id of the previous running command

spin[0]="-"
spin[1]="\\"
spin[2]="|"
spin[3]="/"

echo -n "[copying] ${spin[0]}"
while [ kill -0 $pid ]
do
  for i in "${spin[@]}"
  do
        echo -ne "\b$i"
        sleep 0.1
  done
done

William Pursell的解决方案

/usr/bin/scp me@website.com:file somewhere 2>/dev/null &
pid=$! # Process Id of the previous running command

spin='-\|/'

i=0
while kill -0 $pid 2>/dev/null
do
  i=$(( (i+1) %4 ))
  printf "\r${spin:$i:1}"
  sleep .1
done

答案 1 :(得分:22)

如果您有办法估算完成的百分比,例如当前处理的文件数和总数,您可以制作一个简单的线性进度表,其中包含一些关于屏幕宽度的数学和假设。

count=0
total=34
pstr="[=======================================================================]"

while [ $count -lt $total ]; do
  sleep 0.5 # this is work
  count=$(( $count + 1 ))
  pd=$(( $count * 73 / $total ))
  printf "\r%3d.%1d%% %.${pd}s" $(( $count * 100 / $total )) $(( ($count * 1000 / $total) % 10 )) $pstr
done

或者您可以估算剩余时间而不是线性仪表。它与其他类似的东西一样准确。

count=0
total=34
start=`date +%s`

while [ $count -lt $total ]; do
  sleep 0.5 # this is work
  cur=`date +%s`
  count=$(( $count + 1 ))
  pd=$(( $count * 73 / $total ))
  runtime=$(( $cur-$start ))
  estremain=$(( ($runtime * $total / $count)-$runtime ))
  printf "\r%d.%d%% complete ($count of $total) - est %d:%0.2d remaining\e[K" $(( $count*100/$total )) $(( ($count*1000/$total)%10)) $(( $estremain/60 )) $(( $estremain%60 ))
done
printf "\ndone\n"

答案 2 :(得分:17)

here引用的是一个很好的微调器功能(略有修改),也可以帮助你的光标保持原来的位置。

spinner()
{
    local pid=$!
    local delay=0.75
    local spinstr='|/-\'
    while [ "$(ps a | awk '{print $1}' | grep $pid)" ]; do
        local temp=${spinstr#?}
        printf " [%c]  " "$spinstr"
        local spinstr=$temp${spinstr%"$temp"}
        sleep $delay
        printf "\b\b\b\b\b\b"
    done
    printf "    \b\b\b\b"
}

用法:

(a_long_running_task) &
spinner

答案 3 :(得分:11)

这是一项非常简单的技巧:
(只需将sleep 20替换为您要指示正在运行的任何命令)

#!/bin/bash

sleep 20 & PID=$! #simulate a long process

echo "THIS MAY TAKE A WHILE, PLEASE BE PATIENT WHILE ______ IS RUNNING..."
printf "["
# While process is running...
while kill -0 $PID 2> /dev/null; do 
    printf  "▓"
    sleep 1
done
printf "] done!"

输出如下所示:

> THIS MAY TAKE A WHILE, PLEASE BE PATIENT WHILE ______ IS RUNNING...
> [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] done!

它每秒都会添加一个(高密度点缀),直到过程完成。

答案 4 :(得分:4)

这是我的尝试。我是bash脚本的新手,所以这些代码可能很糟糕:)

示例输出:

In Progress Done

守则:

progressBarWidth=20

# Function to draw progress bar
progressBar () {

  # Calculate number of fill/empty slots in the bar
  progress=$(echo "$progressBarWidth/$taskCount*$tasksDone" | bc -l)  
  fill=$(printf "%.0f\n" $progress)
  if [ $fill -gt $progressBarWidth ]; then
    fill=$progressBarWidth
  fi
  empty=$(($fill-$progressBarWidth))

  # Percentage Calculation
  percent=$(echo "100/$taskCount*$tasksDone" | bc -l)
  percent=$(printf "%0.2f\n" $percent)
  if [ $(echo "$percent>100" | bc) -gt 0 ]; then
    percent="100.00"
  fi

  # Output to screen
  printf "\r["
  printf "%${fill}s" '' | tr ' ' ▉
  printf "%${empty}s" '' | tr ' ' ░
  printf "] $percent%% - $text "
}



## Collect task count
taskCount=33
tasksDone=0

while [ $tasksDone -le $taskCount ]; do

  # Do your task
  (( tasksDone += 1 ))

  # Add some friendly output
  text=$(echo "somefile-$tasksDone.dat")

  # Draw the progress bar
  progressBar $taskCount $taskDone $text

  sleep 0.01
done

echo

您可以在此处查看来源: https://gist.github.com/F1LT3R/fa7f102b08a514f2c535

答案 5 :(得分:3)

除了经典的微调器之外,您还可以使用this progress bar

使用half block characters

实现了字符精度

enter image description here

链接中包含的代码。

答案 6 :(得分:1)

以下是“活动指标”的示例,'通过linux' speedtest-cli'进行互联网连接速度测试命令:

public class AirportItem
{
    public string Name {get;set;}
    public string Country {get;set;}
    public override string ToString()
    {
        return string.Join(", ", this.Name, this.Country);
    }
}

更新 - 示例:

animated GIF

答案 7 :(得分:0)

@DavidD对Pez Cuckows的评论回答,这是一个如何捕获脚本中进度条输出并仍然在屏幕上看到微调器的示例:

#!/usr/bin/env bash 

#############################################################################
###########################################################################
###
### Modified/Rewritten by A.M.Danischewski (c) 2015 v1.1
### Issues: If you find any issues emai1 me at my <first name> dot 
###         <my last name> at gmail dot com.  
###
### Based on scripts posted by Pez Cuckow, William Pursell at:  
### http://stackoverflow.com/questions/12498304/using-bash-to-display-\
###      a-progress-working-indicator
###
### This program runs a program passed in and outputs a timing of the 
### command and it exec's a new fd for stdout so you can assign a 
### variable the output of what was being run. 
### 
### This is a very new rough draft but could be expanded. 
### 
### This program is free software: you can redistribute it and/or modify
### it under the terms of the GNU General Public License as published by
### the Free Software Foundation, either version 3 of the License, or
### (at your option) any later version.
###
### This program is distributed in the hope that it will be useful,
### but WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
### GNU General Public License for more details.
###
### You should have received a copy of the GNU General Public License
### along with this program.  If not, see <http://www.gnu.org/licenses/>.
###########################################################################
#############################################################################

declare    CMD="${1}"
shift      ## Clip the first value of the $@, the rest are the options. 
declare    CMD_OPTIONS="$@"
declare    CMD_OUTPUT=""
declare    TMP_OUTPUT="/tmp/_${0##*/}_$$_$(date +%Y%m%d%H%M%S%N)" 
declare -r SPIN_DELAY="0.1"
declare -i PID=

function usage() {
cat <<EOF

Description: ${0##*/}

This program runs a program passed in and outputs a timing of the 
command and it exec's a new fd for stdout so you can assign a variable 
the output of what was being run. 

Usage: ${0##*/} <command> [command options]

 E.g.  
    >$ ${0##*/} sleep 5 \&\& echo "hello" \| figlet
     Running: sleep 5 && echo hello | figlet, PID 2587:/

     real   0m5.003s
     user   0m0.000s
     sys    0m0.002s
      _          _ _       
     | |__   ___| | | ___  
     | '_ \ / _ \ | |/ _ \ 
     | | | |  __/ | | (_) |
     |_| |_|\___|_|_|\___/ 

     Done..
    >$ var=\$(${0##*/} sleep 5 \&\& echo hi)
     Running: sleep 5 && echo hi, PID 32229:-
     real   0m5.003s
     user   0m0.000s
     sys    0m0.001s
     Done..
     >$ echo \$var
     hi

EOF
} 

function spin_wait() { 
 local -a spin 
 spin[0]="-"
 spin[1]="\\"
 spin[2]="|"
 spin[3]="/"
 echo -en "Running: ${CMD} ${CMD_OPTIONS}, PID ${PID}: " >&3
 while kill -0 ${PID} 2>/dev/random; do
   for i in "${spin[@]}"; do
     echo -ne "\b$i" >&3
     sleep ${SPIN_DELAY}
   done
 done
} 

function run_cmd() { 
 exec 3>$(tty)
 eval "time ${CMD} ${CMD_OPTIONS}" 2>>"${TMP_OUTPUT}" | tee "${TMP_OUTPUT}" & 
 PID=$! # Set global PID to process id of the command we just ran. 
 spin_wait
 echo -en "\n$(< "${TMP_OUTPUT}")\n" >&3 
 echo -en "Done..\n" >&3
 rm "${TMP_OUTPUT}"
 exec 3>&-
} 

if [[ -z "${CMD}" || "${CMD}" =~ ^-. ]]; then 
 usage | more && exit 0 
else 
 run_cmd  
fi 

exit 0 

答案 8 :(得分:0)

bash脚本的迷幻进度条。按命令行调用&#39; ./ progressbar x y&#39;在哪里&#39; x&#39;是一个以秒为单位的时间,而且&#39; y&#39;是要显示的消息。内部函数progressbar()也可以单独工作,并且可以使用&#39; x&#39;百分比和&#39; y&#39;作为一条信息。

#!/bin/bash

if [ "$#" -eq 0 ]; then echo "x is \"time in seconds\" and z is \"message\""; echo "Usage: progressbar x z"; exit; fi
progressbar() {
        local loca=$1; local loca2=$2;
        declare -a bgcolors; declare -a fgcolors;
        for i in {40..46} {100..106}; do
                bgcolors+=("$i")
        done
        for i in {30..36} {90..96}; do
                fgcolors+=("$i")
        done
        local u=$(( 50 - loca ));
        local y; local t;
        local z; z=$(printf '%*s' "$u");
        local w=$(( loca * 2 ));
        local bouncer=".oO°Oo.";
        for ((i=0;i<loca;i++)); do
                t="${bouncer:((i%${#bouncer})):1}"
                bgcolor="\\E[${bgcolors[RANDOM % 14]}m \\033[m"
                y+="$bgcolor";
        done
        fgcolor="\\E[${fgcolors[RANDOM % 14]}m"
        echo -ne " $fgcolor$t$y$z$fgcolor$t \\E[96m(\\E[36m$w%\\E[96m)\\E[92m $fgcolor$loca2\\033[m\r"
};
timeprogress() {
        local loca="$1"; local loca2="$2";
        loca=$(bc -l <<< scale=2\;"$loca/50")
        for i in {1..50}; do
                progressbar "$i" "$loca2";
                sleep "$loca";
        done
        echo -e "\n"
};
timeprogress "$1" "$2"

答案 9 :(得分:0)

我通过在微调器之后显示变量信息消息,在checksum中扩展了his answer的答案:

#!/usr/bin/env bash 
function spinner() {
    local info="$1"
    local pid=$!
    local delay=0.75
    local spinstr='|/-\'
    while kill -0 $pid 2> /dev/null; do
        local temp=${spinstr#?}
        printf " [%c]  $info" "$spinstr"
        local spinstr=$temp${spinstr%"$temp"}
        sleep $delay
        local reset="\b\b\b\b\b\b"
        for ((i=1; i<=$(echo $info | wc -c); i++)); do
            reset+="\b"
        done
        printf $reset
    done
    printf "    \b\b\b\b"
}

# usage:
(a_long_running_task) &
spinner "performing long running task..."

如果带有微调器的stdout输出被重定向到文件,我不会这样,less为每个退格显示^H,而不是在文件输出中完全避免它们。有这样一个简单的旋转器可能吗?

答案 10 :(得分:0)

https://github.com/extensionsapp/progre.sh

创建82%的进度:progreSh 82

enter image description here