Home > Software engineering >  Print correct time on a zshrc command
Print correct time on a zshrc command

Time:07-29

I currently have this code snippet running in my zshrc for an alias where the terminal is supposed to print "Last pushed at ${current time}", laid out below

# custom var 
d=`date  %I:%M`
# aliases
alias gpo="git push origin && echo Last pushed at $d"

the problem is that currently it prints the time as whenever the window last loaded the .zshrc file. For example, if I run source ~/.zshrc at 3:30pm, and then run gpo at 3:45pm, the console prints "Last pushed at 3:30".

The only way I've gotten it to work so far printing the correct time is alias gpo="source ~/.zshrc && git push origin && echo Last pushed at $d".

Is there a better way to write this alias so that it actually prints the correct time every time the alias is run?

CodePudding user response:

@Author,

Initially you set the value for "d" to
d=`date %I:%M`
Later you are using same variable $d
Hence I tested related update using my system:
$ alias gpo='d=`date %I:%M:%S`;echo git push origin && echo Last pushed at $d'
$ gpo
git push origin
Last pushed at 07:54:40
$ gpo
git push origin
Last pushed at 07:54:45

CodePudding user response:

Use the date command directly instead of that $d variable:

alias gpo='git push origin && date " Last pushed at %I:%M"'

For zsh use the print builtin to show the date:

alias gpo='git push origin && print -rP -- "Last pushed at %D{%I:%M}"'

For bash >= 4.1 use the printf builtin:

alias gpo='git push origin && printf "Last pushed at %(%I:%M)T\n" -1'
  • Related