shell製表與腳本運行進度條寫法

1. 其實shell下也可以將輸出的數據以表格的格式輸出,看起來更加直觀些。數據存放的aa文件裏面,以空格/tab/回車分割,數據依次是姓名,年齡,性別,籍貫,序列


#!/bin/bash
# It is a scripts of make tab
# "aa" is filename of store about info,
DI=(`cat aa`)
DATA_NUM=${#DI[*]}
tab_top()
{
echo -n -e "+------------------------------------------------------------------------------+\n"
printf "%-1s %-16s %-1s %-8s %-1s %-8s %-1s %-16s %-1s %-16s %-1s\n" \| name \| age \| sex \| native \| education \|
}
tab_mod()
{
echo -n -e "+------------------+----------+----------+------------------+------------------+\n"
printf "%-1s %-16s %-1s %-8s %-1s %-8s %-1s %-16s %-1s %-16s %-1s\n" \| ${DI[i]} \| ${DI[i+1]} \| ${DI[i+2]} \| ${DI[i+3]} \| ${DI[i+4]} \|
}
tab_end()
{
echo -n -e "+------------------------------------------------------------------------------+\n"
}
clear
tab_top
for (( i=0;i<"$DATA_NUM";i=i+5 ))
do
tab_mod
done
tab_end
exit 0



2. shell 進度條控制

關鍵命令:tput

說  明:這個進度條不是很理想,理想中的應該百分比在進度條後,而且位置固定纔對,只是printf語句不好控制,所以改成了百分比隨進度條移動。另外shell不支持浮點運算,用bc -l算出來的數據取整數在$RATE_MAX不能整除$BAR_NUM是,會出現進度條到99%結束了,所以爲了規避這個錯誤,在後面有添加了

tput rc
tput ed

 printf "%-0s %-15s""$BAR_PRO"" 100% completed."

三句,勉強達到效果。

實際應用,可以下面代碼以模塊的格式拷貝到執行的腳本中,修改$TIME_CONTROL爲你腳本運行的時間,然後模塊以後臺模式運行,記得最後結束語句前加wait語句。


#!/bin/bash
# It is a scripts of process bar.
# Variable "BAR" is use of control process bar color.
# Variable "TIME_CONTROL" is use of control the scripts run time.
# Variable "BAR_NUM" is use of control process bar length.
process_bar()
{
BAR=`echo -e "\033[32;42m \033[0m"`
TOP_NOTE="Starting get system info:"
END_NOTE='done.'
TIME_CONTROL=20
BAR_NUM=25
RATE_MAX=100
PER_TIME=`echo $TIME_CONTROL/$BAR_NUM | bc -l`
PER_RATE=`echo $RATE_MAX/$BAR_NUM | bc -l`
echo -n "$TOP_NOTE "
tput sc
for (( i=1;i<=$BAR_NUM;i++ ))
do
tput rc
tput ed
BAR_PRO=$BAR_PRO$BAR
I=`echo $PER_RATE*$i | bc -l | awk -F . '{print $1}'`
printf "%-0s %-15s" "$BAR_PRO" "$I% completed."
sleep $PER_TIME
done
tput rc
tput ed
printf "%-0s %-15s" "$BAR_PRO" " 100% completed."
}
process_bar &
sleep 20
wait
echo
echo "done."
exit 0


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章