寫 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。
- #!/bin/bash
- #Description: A shell script to copy parameter1 to parameter2 and Display a progress bar
- #Author:Jacob
- #Version:0.1 beta
- # Read the parameter for copy,$1 is source dir and $2 is destination dir
- dir=$1/*
- des=$2
- # Test the destination dirctory whether exists
- [ -d $des ] && echo "Dir Exist" && exit 1
- # Create the destination dirctory
- mkdir $des
- # Set counter, it will auto increase to the number of source file
- i=0
- # Count the number of source file
- n=`echo $1/* |wc -w`
- for file in `echo $dir`
- do
- # Calculate progress
- percent=$((100*(++i)/n))
- cat <<EOF
- XXX
- $percent
- Copying file $file ...
- XXX
- EOF
- /bin/cp -r $file $des &>/dev/null
- done | dialog --title "Copy" --gauge "files" 6 70
- clear
這裡有兩個值得留意的技巧:一是用 wc -w 搭配檔案展開來取得總數,二是透過 heredoc 輸出「XXX、百分比、描述文字、XXX」這段 dialog 認得的通訊協定,再整條管線餵給 --gauge。
效果如圖: