加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在shell脚本中显示进度指示器功能?

发布时间:2020-12-15 17:01:56 所属栏目:安全 来源:网络整理
导读:我想在我的脚本中编写一个进度指示器函数,它循环“请等待”消息,直到完成调用它的任务. 我希望它是一个函数,以便我可以在其他脚本中重用它. 为了实现这一点,函数需要与其他函数松散耦合,即调用它的函数不必知道其内部代码. 这是我到目前为止所拥有的.此函数
我想在我的脚本中编写一个进度指示器函数,它循环“请等待”消息,直到完成调用它的任务.

我希望它是一个函数,以便我可以在其他脚本中重用它.

为了实现这一点,函数需要与其他函数松散耦合,即调用它的函数不必知道其内部代码.

这是我到目前为止所拥有的.此函数接收调用者的pid并循环,直到任务完成.

function progress() {
  pid="$1"

  kill -n 0 "${pid}" &> /dev/null && echo -ne "please wait"
  while kill -n 0 "${pid}" &> /dev/null ; do
    echo -n "."
    sleep 1
  done
}

在脚本中使用它时,它可以正常工作,例如:

#imports the shell script with the progress() function
. /path/to/progress.sh

echo "testing"
# $$returns the pid of the script.
progress $$&
sleep 5
echo "done"

输出:

$testing
$please wait.....
$done

问题是当我从另一个函数调用它时,因为函数没有pids:

function my_func() {
  progress $$&
  echo "my func is done"
}

. /path/to/progress.sh
echo "testing"
my_func
sleep 10
echo done

输出:

$testing
$please wait.....
$my func. is done.
$..........
$done
您可能对对话框感兴趣 – bash curses面向菜单系统.

对于进度条,您可以查看http://bash.cyberciti.biz/guide/A_progress_bar_(gauge_box)

或者,另一个更简单的项目:
http://www.theiling.de/projects/bar.html

如果不感兴趣,你可以尝试下一个:

dotpid=
rundots() { ( trap 'exit 0' SIGUSR1; while : ; do echo -n '.' >&2; sleep 0.2; done) &  dotpid=$!; }
stopdots() { kill -USR1 $dotpid; wait $dotpid; trap EXIT; }
startdots() { rundots; trap "stopdots" EXIT; return 0; }

longproc() {
    echo 'Start doing something long... (5 sec sleep)'
    sleep 5
    echo
    echo 'Finished the long job'
}

run() {
    startdots
    longproc
    stopdots
}

#main
echo start
run
echo doing someting other
sleep 2
echo end of prog

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读