Search code examples
linuxshellzsh

How do I check if nothing was typed in the previous Zsh prompt


In the zsh prompt, I have a custom script to display the amount of time the last command ran for.

I've got this working, but how do I check if the user entered nothing and just pressed "Enter" or "Ctrl + C", in the previous prompt?

In this case, I do not want to show the amount of time the user spent idle, as this is not useful information for me.

$history[$((HISTCMD-1))] doesn't appear to work in this case. If the user typed nothing and just hit enter, it will just show the last command that was run, and not be an empty string.


Solution

  • If you define a function with the name zshaddhistory, it will be invoked every time enter has been pressed. $1 is the command being entered, and this can also be an empty command. You could set a global variable to indicate that an empty line has been entered, and use this variable later on.

    Be careful with the return value from this function: If it returns 0, the command is saved into the history; otherwise it is not. You find more on this in the zshparam man-page, where _HISTORY_IGNORE_ is described, because the main use of this function is to control whether or not a command should be added into the history. Hence, an alternative would be to add empty lines to the history too and use your original approach with $history to access it. This has the disadvantage that seeing empty history entries is not really user-friendly.