How can the last command's wall time be put in the Bash prompt?

后端 未结 14 2825
無奈伤痛
無奈伤痛 2020-12-04 05:16

Is there a way to embed the last command\'s elapsed wall time in a Bash prompt? I\'m hoping for something that would look like this:

[last: 0s][/my/dir]$ sl         


        
14条回答
  •  暖寄归人
    2020-12-04 05:57

    Translated version for zsh.

    Append to your ~/.zshrc file

    function preexec() {
      timer=$(date +%s%3N)
    }
    
    function precmd() {
      if [ $timer ]; then
        local now=$(date +%s%3N)
        local d_ms=$(($now-$timer))
        local d_s=$((d_ms / 1000))
        local ms=$((d_ms % 1000))
        local s=$((d_s % 60))
        local m=$(((d_s / 60) % 60))
        local h=$((d_s / 3600))
        if ((h > 0)); then elapsed=${h}h${m}m
        elif ((m > 0)); then elapsed=${m}m${s}s
        elif ((s >= 10)); then elapsed=${s}.$((ms / 100))s
        elif ((s > 0)); then elapsed=${s}.$((ms / 10))s
        else elapsed=${ms}ms
        fi
    
        export RPROMPT="%F{cyan}${elapsed} %{$reset_color%}"
        unset timer
      fi
    }
    

提交回复
热议问题