Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save the current working directory to Zsh history?

Tags:

shell

zsh

zshrc

I wanted to achieve the same as asked here Saving current directory to bash history but within Zsh shell. I haven't done any Zsh trickery before but so far I have:

function precmd {
  hpwd=$history[$((HISTCMD-1))]  
  if [[ $hpwd == "cd" ]]; then  
    cwd=$OLDPWD
  else
    cwd=$PWD
  fi
  hpwd="${hpwd% ### *} ### $cwd"
  echo "$hpwd" >>~/.hist_log
}

Right now I save the command annotated with the directory name to a log file. This works fine for me. Just thought there might be a way to make the same replacement in the history buffer itself.

like image 442
Sandeep Avatar asked May 13 '10 02:05

Sandeep


People also ask

How do I turn on history in ZSH?

To view all the commands stored in your ZSH history file, use the history command. In most cases, the history command will display an extensive list of all your executed commands. You can pipe the output to commands such as grep to search for a specific command or less to navigate it easily.

How do you go back a directory in ZSH?

If I can quickly change directories ( cd ) to anywhere in my computer's file system, how can I go back if I mistakenly navigate away from somewhere I was working? Turns out that Bash (and Zsh) allow a quick return by using $ cd - .

How long is ZSH history?

Increasing the History File Size Unfortunately, zsh's default history file size is limited to 10000 lines by default and will truncate the history to this length by deduplicating entries and removing old data. Adding the following lines to . zshrc will remove the limits and deduplication of the history file.

Which is better Bash or ZSH?

Zsh is more interactive and customizable than Bash. Zsh has floating-point support that Bash does not possess. Hash data structures are supported in Zsh that are not present in Bash. The invocation features in Bash is better when comparing with Zsh.


1 Answers

function _-accept-line() {
    [[ -z "${BUFFER" ]] || [[ "${BUFFER}" =~ "### ${(q)PWD}\$" ]] || BUFFER="${BUFFER} ### ${PWD}"
    zle .accept-line
}
zle -N accept-line _-accept-line

Will add ### ${PWD} to your command line. Not the best solution you could use, but it works.

UPD: Answer based on @Dennis Williamson's comment:

function zshaddhistory() {
    print -sr "${1%%$'\n'} ### ${PWD}"
    fc -p
}
like image 165
ZyX Avatar answered Nov 09 '22 01:11

ZyX