zsh:显示命令花费的时间

标签 zsh

我有一些长时间运行的命令,可以持续 15 分钟或更长时间。

有没有办法在输出中输出动态“花费的时间”部分?

例如

$ `do something long`
10 mins 15 secs
Refreshing state...

然后:

$ `do something long`
14 mins 15 secs
Refreshing state...
Output results
$ ... and we're done

最佳答案

zmodload -F zsh/system p:sysparams # Load the sysparams table.
zmodload -F zsh/terminfo b:echoti  # Load the echoti builtin.

timed() {
  local +h -i SECONDS=0

  # Open an async process for the timer.
  local -i timer_fd
  exec {timer_fd}< <(
    # Print the process id, so we can kill it later.
    print $sysparams[pid] 

    echoti civis   # Make the cursor invisible.

    while true; do
      print "$(( SECONDS / 60 )) mins, $(( SECONDS % 60 )) secs"
      echoti cuu1  # Move the cursor up 1 line.
    done
  )

  # Read the timer process id.
  local -i timer_pid
  read timer_pid <&$timer_fd

  # Start another async process for the actual task.
  local -i task_fd
  exec {task_fd}< <(
    eval "$@"     # Run the task.

    # Close the timer fd and kill the timer process.
    exec {timer_fd}<&-
    kill -KILL $timer_pid

    echoti cnorm  # Make the cursor normal again.
  )

  # Redirect the output of the async processes to the terminal. This is
  # a blocking operation. Thus, we won't get past these two lines until
  # both async processes end.
  <&$timer_fd
  <&$task_fd

  exec {task_fd}<&-  # We're done. Close the task fd.
}

使用示例:

% timed 'sleep 855; print Output results'

引用文献

关于zsh:显示命令花费的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65308912/

相关文章:

git - Brew Git Bash Completion with zsh

ruby - Rbenv 和两个版本的 Heroku 客户端

python - 我们可以使用任何 Python 工具验证 USDZ 模型吗?

java - 使用basename在java中命名输出文件

linux - .zshrc 中最有效的 if 语句来检查 Linux 操作系统是否在 WSL 上运行?

ruby - RVM 首先在 $PATH 中加载

git 添加自动完成文件名

homebrew - 安装 ohmyzsh 声称 zsh 未安装

linux - 显示或重定向 shell 的作业控制消息

linux - 一般如何将可执行文件添加到用户路径