使用Bash显示进度指示器

问题描述:

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

Using a bash only script, how can you provide a bash progress indicator?

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

So I can run a command form bash, and while that command is executing let the user know that something is still happening.

在此示例中,使用SCP,我演示了如何获取进程ID(pid),然后在该进程运行时执行某些操作.

In this example using SCP, I'm demonstrating how to grab the process id (pid) and then do something while that process is running.

这将显示一个简单的旋转图标.

This displays a simple spinnng icon.

/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's solution

/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