1

By executing this command,

❯ fc -l -1 | awk 'END{print $1}'
8845

I can see that I have 8845 commands in my history file. And I'm using , so my history file looks like this:

❯ head $HISTFILE                    
: 1575981231:0;exit 
: 1575981278:0;git clone --depth=1 https://github.com/romkatv/powerlevel10k.git $ZSH_CUSTOM/themes/powerlevel10k
: 1575981423:0;clear
: 1575981457:0;exit 
: 1575981463:0;sudo vim ~/.zshrc
: 1575981490:0;source $_
: 1575981540:0;exit 
: 1575981684:0;git clone https://aur.archlinux.org/yay.git
: 1575981688:0;cd yay
: 1575981692:0;makepkg -si

So I can find my first command, like this:

❯ head -n 1 $HISTFILE
: 1575981231:0;exit 

I understand that this time is Unix Time. I want to find out how much time has passed since I entered that command into my terminal, in a readable format like this: 2 days, 2 hours, 5 minutes, and 54 seconds

How can I do that?

1

First, we need to find the Unix time of the first command, then we can subtracts that time from the current time and convert it to a human-readable format.

❯ awk -F: 'NR==1{print $2}' ~/.zsh_history | tr -d ' ' 
1575981231

This command takes the first line of ~/.zsh_history file and separates it by : and then prints its second field, which is the time we needed. We also trim extra spaces from the output of awk by piping it to tr -d ' '. So now we have the time of the first command. Now we need the current time, in Unix. That can be simply done via this command:

❯ date +'%s'                               
1578207763

All that is left to do is to subtract the first time from the current time and convert it. Here's a bash script to do just that:

#!/bin/bash
# tsfc - time since first command
function display_time {
    local T="$1"
    local D="$((T/60/60/24))"
    local H="$((T/60/60%24))"
    local M="$((T/60%60))"
    local S="$((T%60))"

    (( $D > 0 )) && printf '%d days, ' $D
    (( $H > 0)) && printf '%d hours, ' $H
    (( $M > 0)) && printf '%d minutes, ' $M
    (( $D > 0 || $H > 0 || $M > 0)) && printf 'and '
    printf '%d seconds\n' $S
}

first="$(awk -F: 'NR==1{print $2}' ~/.zsh_history | tr -d ' ')"
now="$(date +'%s')"
difference=$((now - first))

display_time $difference

The function in this script is taken from Stéphane Gimenez's answer on Unix.StackExchange, which displays the time we give it (in seconds) in a human-readable format.

Now you can write that script in a file, make it executable, copy it into /usr/bin and everytime you run it, you can see the time that has passed since the first command you executed in zsh.

tsfc howto

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.