您的位置:首页 > 运维架构 > Shell

shell之图形进度条

2015-10-14 21:37 253 查看
在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中提供进度的显示。该脚本有两个参数,第一个参数为源文件路径,第二个参数为目标路径。如果您的应用案例不同可以据此稍作修改即可使用。
#!/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


效果如图:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: