Skip to main content

顯示進度 progress

範例:簡易版
echo -ne '>>>                       [20%]\r'
# some task
sleep 2
echo -ne '>>>>>>>                   [40%]\r'
# some task
sleep 2
echo -ne '>>>>>>>>>>>>>>            [60%]\r'
# some task
sleep 2
echo -ne '>>>>>>>>>>>>>>>>>>>>>>>   [80%]\r'
# some task
sleep 2
echo -ne '>>>>>>>>>>>>>>>>>>>>>>>>>>[100%]\r'
echo -ne '\n'
範例:顯示進度條
#!/bin/bash
#
# inprogress.sh
# Description: this script may show some simple motion in foreground
# when main program in progress.
# Author: A-Lang (alang[dot]hsu[at]gmail[dot]com)

trap 'kill $BG_PID;echo;exit' 1 2 3 15

function waiting
{
INTERVAL=0.5
TT='->——
–>—–
—>—-
—->—
—–>–
——>-
——->
——<-
—–<–
—-<—
—<—-
–<—–
-<——
<——-';
echo -ne "Please waiting… "
while true
do
for j in $TT
do
echo -ne "Please be patient, $j"
sleep $INTERVAL
done

done
}

# Start the waiting, where place your main program.
waiting &
BG_PID=$!

sleep 10

# End of the waiting
kill $BG_PID
echo

範例:模擬Linux loading kernel

#!/bin/sh
#輸出"."進度條函數,兼容bsh、ksh、bash
#首先trap 1 2 3 15信號,重要

trap 'kill $BG_PID;echo;exit' 1 2 3 15

function dots
{
stty -echo >/dev/null 2>&1
while true
do
  echo ".c"
  sleep 1 
done
stty echo
echo
}

#———————————————
# 主程序開始
#———————————————

#首先使dots函數後台運行
dots &
BG_PID=$!

#開始程序主體,本例中執行休眠10秒
#注意必要時使用 >/dev/null 2>&1關閉輸出和錯誤回顯,避免破壞顯示
sleep 10

#程序結尾注意kill dots,否則dots會一直執行
kill $BG_PID
範例:整合 LED 的顯示
#!/bin/bash

echo "Starting to format the disk...."

# Start to blink the LED
/root/bin/led.sh b
/root/bin/led.sh blink &
led_pid=$!

# Main codes
echo "formating hdisk2..."
sleep 10

# When the main codes is ending up
# Stop to blink the LED
kill -9 $led_pid
wait $led_pid 2>/dev/null
sleep 2

# Making sure the LED is ON with Blue
/root/bin/led.sh b
echo "done"

led.sh 用來控制 LED 的閃燈

wait .... 這行用來隱藏 killed ... 的文字訊息