shell之图形进度条


在Shell脚本的编写应用中,有时候会需要用到图形界面的案例,比如默认cp拷贝文件为静默模式,无法看到拷贝的进度与百分比。而dialog正是为Shell提供图形界面的工具,该工具可以为Shell脚本提供各式各样的图形界面,今天为大家介绍的是dialog提供的进度条图形功能。

dialog指令可以单独执行,各式为dialog --title "Copy" --gauge "files" 6 70 10

备注:title表示图形进度条的标题,gauge为正文内容,进度条高度为6,宽度70,显示进度为10%

for i in {1..100} ; do sleep 1; echo $i | dialog --title 'Copy' --gauge 'I am busy!' 10 70 0; done

下面案例中通过统计源文件个数,再据此计算出拷贝文件的百分比,在Shell中提供进度的显示。该脚本有两个参数,第一个参数为源文件路径,第二个参数为目标路径。如果您的应用案例不同可以据此稍作修改即可使用。

  1. #!/bin/bash
  2. #Description: A shell script to copy parameter1 to parameter2 and Display a progress bar
  3. #Author:Jacob
  4. #Version:0.1 beta
  5. # Read the parameter for copy,$1 is source dir and $2 is destination dir
  6. dir=$1/*
  7. des=$2
  8. # Test the destination dirctory whether exists
  9. [ -d $des ] && echo "Dir Exist" && exit 1
  10. # Create the destination dirctory
  11. mkdir $des
  12. # Set counter, it will auto increase to the number of source file
  13. i=0
  14. # Count the number of source file
  15. n=`echo $1/* |wc -w`
  16. for file in `echo $dir`
  17.   do
  18. # Calculate progress
  19. percent=$((100*(++i)/n))
  20. cat <<EOF
  21. XXX
  22. $percent
  23. Copying file $file ...
  24. XXX
  25. EOF
  26. /bin/cp -r $file $des &>/dev/null
  27.   done | dialog --title "Copy" --gauge "files" 6 70
  28. clear

效果如图:

相关内容