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

后端 未结 14 2838
無奈伤痛
無奈伤痛 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

    A version with split hours, minutes and seconds inspired by the zsh spaceship prompt, based on Ville's answer and this time conversion function by perreal.

    I also added a threshold variable so that the timer only displays for long running commands.

    time_threshold=5;
    
    function convert_secs {
        ((h=${1}/3600))
        ((m=(${1}%3600)/60))
        ((s=${1}%60))
        if [ $h -gt 0 ]; then printf "${h}h "; fi
        if [ $h -gt 0 ] || [ $m -gt 0 ]; then printf "${m}m "; fi
        if [ $s -gt 0 ]; then printf "${s}s "; fi
    }
    
    function timer_start {
        timer=${timer:-$SECONDS}
    }
    
    function timer_stop {
        timer_time=$(($SECONDS - $timer))
        
        if [ ! -z $timer_time ] && [ $timer_time -ge ${time_threshold} ]; then
            timer_show="took $(convert_secs $timer_time)"
        else
            timer_show=""
        fi
    
        unset timer
    }
    
    trap 'timer_start' DEBUG
    PROMPT_COMMAND=timer_stop
    
    PS1='\n\w ${timer_show}\n\\$ '
    

    For the coloured output in my screenshot:

    bold=$(tput bold)
    reset=$(tput sgr0)
    yellow=$(tput setaf 3)
    cyan=$(tput setaf 6)
    
    PS1='\n${bold}${cyan}\w ${yellow}${timer_show}${reset}\n\\$ '
    

提交回复
热议问题