Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

用 dialog 為 Shell 腳本加上圖形進度條

寫 Shell 腳本時,難免會需要一點圖形化的回饋。最典型的例子就是 cp 拷貝檔案預設是靜默模式,使用者完全看不到進度與百分比,長時間的批次複製更令人焦慮。這時 dialog 就能派上用場——它為 Shell 提供了各式各樣的圖形介面元件,本文聚焦其中的進度條功能。

dialog 的單獨使用

dialog --title "Copy" --gauge "files" 6 70 10

參數依序是:title 為進度條標題,gauge 為正文內容,接著是高度 6、寬度 70,最後的 10 代表目前進度 10%。

若想让進度動起來,可以搭配迴圈:

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

實戰:拷貝目錄並顯示百分比

下面的腳本先統計來源檔案數量,再依此算出拷貝百分比,即時呈現進度。它接受兩個參數:第一個是來源路徑,第二個是目標路徑,如果你的情境不同,稍加修改即可 reuse。

  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

這裡有兩個值得留意的技巧:一是用 wc -w 搭配檔案展開來取得總數,二是透過 heredoc 輸出「XXX、百分比、描述文字、XXX」這段 dialog 認得的通訊協定,再整條管線餵給 --gauge。

效果如圖:

Copyright © Linux教程網 All Rights Reserved