1) Ctrl + P Just press the Ctrl and P keys together to fill the prompt with the last executed command and you are ready to go.
ZSH is a popular shell built on top of bash. It stores your command history in the . zsh_history file in your home directory. If your ZSH shell does not support command history by default, check out our zsh command history article to learn how to enable it.
After you have typed what you are looking for, use the CTRL-R key combination to scroll backward through the history. Use CTRL-R repeatedly to find every reference to the string you've entered.
The most obvious one is, of course, to verify whether the last command is executed properly, especially if the command doesn't generate any output. In the case of bash, the exit code of the previous command is accessible using the shell variable “$?”.
Is there a way to retrieve the text of the last command in Zsh? I mean the last executed command, not the last command line.
Trying to do it, I discovered a subtle difference between Zsh and Bash handling of history. This difference is exposed in the following sample, which is the base of what I was doing in Bash, and which does not work in Zsh.
$ zsh
$ echo "This is command #1"
> This is command #1
$ echo "This is command #2"; echo $(history | tail -n1)
> This is command #2
> 3807 echo "This is command #1"
$ bash
$ echo "This is command #1"
> This is command #1
$ echo "This is command #2"; echo $(history | tail -n1)
> This is command #2
> 4970 echo "This is command #2"; echo $(history | tail -n1)
Same tests, whose result differs in the last line. Bash appends the command line to the history, before execution (I don't know if it's by specification), while Zsh seems to append the command line to the history, after execution (the same, I don't know if it's by specification), thus history | tail -n1
does not give the same.
What I want, is to be able to retrieve echo "This is command #2"
, that is, the text of the previous command even when it's on the same command line as other commands (when there are multiple command separated with ;
).
With bash, I could use history | tail -n1 | sed ...
, but this does not work any more with Zsh, due the difference in history handling.
Any idea on how to get the last command from a multi‑command command line in Zsh?
I need it for when a command needs to know what was the previous command, whatever that command was on the same line or the previous line. Another way to say it, could be: I need to access the last item of a single command oriented history, not of a command(s) line oriented history.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With