Delete specific line from Zsh history - macos

I'd like to remove a specific entry in my Zsh history.
Zsh's fc and history don't have any options to delete entries. I've tried looking for the ~/.zhistory but that doesn't exist. How can I go about finding the location of the history file and remove the entry?

You are looking in wrong File. Look at ~/.zsh_history not ~/.zhistory To view in which file your history is saved:
echo $HISTFILE
And delete:
rm $HISTFILE

Clearing Zsh History (oh-my-zsh)
close, quit and re-open iTerm
run nano .zsh_history
use the arrow keys to navigate to the part of your history you'd like to delete.
use the delete key to remove all unwanted history logs.
Once you've removed everything you'd like to remove, select control X to Exit.
You'll be prompted to Save the changes. If you're happy with your changes click shift Y.
You'll be asked where you'd like to save your changes. Select control T to save to File.
navigate to your .zsh_profile with your arrow keys and press enter.
Quit and restart iTerm.
type history to confirm the deletions.
You've successfully cleared your Zsh history.
osxterminalzshoh-my-zsh

Clear zsh history on unix systems.
echo "" > ~/.zsh_history & exec $SHELL -l

open ~/.zshrc
add the following line
alias clear_history='echo "" > ~/.zsh_history & exec $SHELL -l'
Save and close the file
Close the console or type zsh
if you to see the result directly, but this will open another zsh shell in the old one
Now you can clear the console typing clear_history
All the previous answers are good, this is simply the solution that worked for me.

You can use these commands to open the ZSH command's history(When you are in the home or ~ directory) and assume that you know how to use vim or nano :
nano ~/.zsh_history
vim ~/.zsh_history
open ~/.zsh_history
then you can delete the lines you want manually and save the file.
and if your zsh_history list is too long, for convenience use this:
enable mouse move and line numbering in the Vim environment by adding this to .vimrc:
open .vimrc:
vim ~/.vimrc
add these to .vimrc and save it(press ESC, enter ":" , write wq, and press enter):
:set number
set mouse=a
use the mouse to scroll easily in zsh_history by using Vim.
if you want to enable copy in Vim use holding shift on the keyboard.

read this for more info
https://www.techrepublic.com/article/how-to-effectively-clear-your-bash-history/
TL;DR
cat /dev/null > ~/.zsh_history

Type and run at the zsh command line, openĀ ~/.zsh_history (This opens TextEdit on my Mac.)
Delete any lines in the file
Save and close the file
Close/Exit the Zsh completely and restart the Zsh (this step is important!)
Now, open zsh and the history command does not show the lines that you deleted

This function will remove any one line you want from your Zsh history, no questions asked:
# Accepts one history line number as argument.
# Alternatively, you can do `dc -1` to remove the last line.
dc () {
# Prevent the specified history line from being saved.
local HISTORY_IGNORE="${(b)$(fc -ln $1 $1)}"
# Write out history to file, excluding lines that match `$HISTORY_IGNORE`.
fc -W
# Dispose of the current history and read the new history from file.
fc -p $HISTFILE $HISTSIZE $SAVEHIST
# TA-DA!
print -r "Deleted '$HISTORY_IGNORE' from history."
}
If you additionally want to prevent all dc commands from being written to history, add the following in your ~/.zshrc file:
zshaddhistory() {
[[ $1 != 'dc '* ]]
}
Alternatively, for a comprehensive, out-of-the-box solution, use my Zsh Hist plugin.

E.g. with vim you can easily delete the last n lines like this:
Open file: vim ~/.zsh_history
Go to the bottom of the file: G
Mark lines: V -> move up with arrow key
Delete: d
Write & quit: :wq
Or you can just navigate with the cursor and delete any particular line with dd

Open .zsh_history with your favourite editor and save keystrokes.
e.g. subl .zsh_history will open up history in Sublime editor and then delete whatever you want.
You can use TextEdit or other editors also.

This worked for me:
LC_ALL=C sed -i '' '/line/d' $HISTFILE
Replace "line" with what you want deleted.
From this answer:
https://stackoverflow.com/posts/13661794/revisions

For ZSH
To locate the history file do :
echo $HISTFILE
Then simply edit the file and remove any lines you wish to be gone as you would with history -d id.
Save the file.
Open a new terminal and you should see that there is nothing to see anymore !
However I am amazed that history -d does not exists. If it does exists it's well hidden.

Related

aliases are not stored in zsh history

Whenever I execute a command using an alias, this command is not stored in the shell's command history.
So if I run history these commands do not appear in the list.
Nor do they appear when I press CTRL + r for reverse searching the command history.
When I press the keyboard's arrow up for scrolling through the last commands, I will see an aliased command only if it was the last command I ran. Other aliased commands are will not be displayed.
For example:
$ cd my-repo
$ gs # an alias to git status
$ history
Outputs the following:
2374 cd my-repo
(the gs command is not displayed)
A few notes:
gs is only an example. The issue is far more annoying in more complex commands since I have to retype them all over again instead of executing them from history (e.g. k get pods | grep <pod_name>, where k=kubectl).
gs is defined so: alias gs=' git status'.
I also have a few functions in ~/.alias, e.g.:
mkcd () {
mkdir -pv $1
For some reason, mkcd (or any other function in the alias file) is included in the history.
I do not mind if it prints out gs or expands to git status, I'll take any of the two...
I am using zsh with oh-my-zsh on macOS (Monterey). My shell aliases are defined in ~/.alias which is sourced in ~/.zshrc (source ~/.alias).
This happens both in iTerm2 and in the default Mac terminal.
Thank you for taking the time to help :-)
I will assume that your example alias is exactly what you have in your ~/.alias file.
So you have aliases like this (notice the space character in front of git command):
alias gs=' git status'
There is an shell option called HIST_IGNORE_SPACE which is doing exactly what you are experiencing - in short it will not add command to the history when it starts with space character. Example:
echo 'This command will make it to the history.'
echo 'This poor command will be forgotten.'
You can check your current options using setopt or specifically:
setopt | grep 'histignorespace'
So there are two ways how you can fix this - either by fixing your aliases to not start with space or, If you really don't want this functionality at all, by unsetting it in your ~/.zshrc like this:
unsetopt HIST_IGNORE_SPACE

Searching your command history on macOS terminal

What is the shortcut to search my command history in macOS terminal?
For how long is the history available for searching? Where is it stored?
How about using Ctrl+R for searching on the Terminal Utility in Mac for searching on the command history,
dudeOnMac: freddy$ whoami
freddy
(reverse-i-search)`who': whoami
Well for controlling how long the history would be retained that depends on a few shell environment variables, HISTFILESIZE which is nothing but number of lines of history you want to retain. Set a huge value for it in .bash_profile for it to take effect
HISTFILESIZE=10000000
Use Ctrl + R for searching a command from history in Terminal.
(reverse-i-search)`':
Type any substring of the command you want to search e.g. grep
(reverse-i-search)`grep': grep "XYZ" abc.txt
It will return the latest command that matches your input. If that is not the command you were searching for, keep pressing Ctrl + R for next match until you find your command.
Once you found your command press Return to execute it.
If you want to exit without running any command, press Ctrl + G
PS: This answer is same as suggested by Inian, just giving more details for easy usage.
The command history is stored under your home folder in a hidden file called .bash_history. To view it's content in nano, use the following command in Terminal:
nano ~/.bash_history
Or open with your text editor (default is TextEdit):
open ~/.bash_history
In my case it's a very long list and as I scroll through seems like the last ~500 command is stored here.
Migrating an answer to SO from this answer on the Unix and Linux Stack Exchange:
Pressing ctrl+R will open the history-search-backward. Now start typing your command, this will give the first match. By pressing ctrl+R again (and again) you can cycle through the history.
If you like to be super lazy you can bind the up/down arrow keys to perform this search, I have the following in my .inputrc to bind the up/down arrow key to history-search-backward and history-search-forward:
# Key bindings, up/down arrow searches through history
"\e[A": history-search-backward
"\e[B": history-search-forward
"\eOA": history-search-backward
"\eOB": history-search-forward
Just type something (optional), then press up/down arrow key to search through history for commands that begin with what you typed.
To do this in .bashrc rather than .inputrc, you can use:
bind '"\e[A": history-search-backward'
Use this command -
history
This works on both OSX and Linux.
History is stored in ~/.zsh_history or ~/.bash_history or ~/.history depending on your shell.
History is stored for 1000 or 2000 lines depending on your system.
echo $HISTSIZE
You can also try the following:
history | grep 'git'
Where 'git' is the command you are looking for.
For those who want to search specific command from history, you can do so with reverse-i-search. Reverse search allow you to type in any key words(any) that is part of the command you are looking for and reverse search navigate back to history, match previous commands incrementally and return the entire command.
It is especially useful as when one cannot remember all handy lengthy commands they use often. To do reverse-search ctrl + R and type any clue you have and that will return your previous commands matching the words you type. Then once found the command, hit Enter to execute it directly from search.
Automation AppleScript
Since you mentioned viewing your history as a quick solution, via the Terminal.app. You might want to automate, or quickly view history, maybe from the dock. You may use the AppleScript application as one alternative. This is an optional approach to create a simple shortcut, as to many others.
Open the AppleScript editor application.
Add your specified commands, for history.
Code
tell application "Terminal"
do script "history"
end tell
Save as application, drag to dock for convenience.
History Storage & Time Stored Details
HISTSIZE Determines how many lines will be written to the history file.
HISTFILESIZE Determines how long the file.
Find out how long history is stored:
echo $HISTSIZE $HISTFILESIZE
Note: You may also increase your command history storage size in the length of two variables. You may achieve this through HISTSIZE and HISTFILESIZE environment variables which are located in your ~/.bash_profile file.
It is possible to achieve this by modifying ~/.bash_profile, the number placeholder with SIZE represent's the number, lines value as example:
export HISTFILESIZE=SIZE # Example 1000
export HISTSIZE=SIZE # Example 10000
Pre macOS 11 Big Sur
cat ~/.bash_history
HISTFILESIZE will only set a maximum history value which is stored to the history file when a session is started. HISTSIZE will determine specifically how many lines will be stored or in other words, written at the end of the session. If the set HISTFILESIZE is determined to be a large value than what HISTSIZE is set, you will not view history larger than your set HISTSIZE. The reason is that the history file is overwritten with the HISTSIZE unless using histappend option turned ON.
You may use also histappend to append history, If the histappend shell option is turned on lines are appended to the history file. Otherwise, the overwritten alternative proceeds.
Bash GNU - histappend
macOS 11 Big Sur
nano ~/.zprofile
Modify history environment variables, set to a value:
export HISTFILESIZE=1000
export HISTSIZE=SIZE=1000
Run the source command can be used to load any functions file into the current shell script or a command prompt.
source ~/.zprofile
echo $HISTSIZE $HISTFILESIZE
Outputs:
1000 1000
Output where some history is stored:
cat ~/.zsh_history
For macOS Big Sur the file is now .zsh_history
If you do vi ~/.zsh_history in the terminal you can use regex by pressing the / and then the search term.
To review or recall recently used commands, you can just press the up arrow key to sequentially read back through the history stored in .bash_history.
To search through history with ease, I advise you to install fzf.
It's an interactive Unix filter for command-line that can be used with any list; files, command history, processes, hostnames, bookmarks, git commits, etc.
Just install it, click ctrl + R, and you'll be to scroll through you shell history, without the need to grep or waiting ages until the command you're waiting for pops up.
It supports Mac OS, Linux and even Windows.
# USAGE: find.history cd
# filter commands in shell history by a search term and execute the selected command
function find.history {
eval $(history | grep "$1" | tail | awk '{$1=""}1' | tail -r | peco)
}
You will need to have peco installed.
https://github.com/peco/peco
[$]> brew install peco

Can I open a file with geany from the terminal

I know there is a shortcut to open a file with sublime text from the terminal but id there something similar with geany, the only info I can find online about it is opening a file from geany to the terminal.
If Geany is inside your path, just call geany <file>. This should work on every platform, Geany is running.
Out of Geany's man page:
SYNOPSIS
geany [option] [+number] [files ...]
This will open files either in a new session or, if already a session of Geany is running, inside the existing one.
A file can be given as space separated list and might take even line numbers:
files ...
A space-separated list of filenames. Absolute and relative
filenames can be used. Geany also recognises line and column
information when appended to the filename with colons, e.g.
"geany foo.bar:10:5" will open the file foo.bar and place the
cursor in line 10 at column 5.
You can use open:
open [PATH_TO_FILE] -a [PATH_TO_GEANY_APP]
The a option defines which application to use.
To make this shorter, create an alias:
Something like echo 'alias geany="open $1 -a [PATH_TO_GEANY_APP]"' >> ~/.bash_profile && chmod u+x ~/.bash_profile. Then open a new Terminal window and type geany [path_to_file].

How can I create and open a file from terminal with a single command?

To create a file from terminal I type the following...
$ touch filename.py
To open the file I just created from terminal, I then type...
$ open filename.py
I'm curious to know if there is a terminal command that does both...create and then open (I'm super lazy).
in .bashrc
lazytouch()
{
touch $1
open $1
}
then type
$ lazytouch anything.really
This is as lazy as one can get:
$ echo "your text" > myfile.txt
Simplest way to do this is
touch filename; open filename
Example
touch myfile.py; open myfile.py
What I do when I want to create a file, edit it and just save it is I type vim at the terminal. vim is a text editor. If you just type in vim you would see the text editor.
But if you type for instance vim example.txt you open vim and from then on you are working in the file you created. The file does not get saved until you say so. So by pressing i you enter the edit mode of vim. Allowing you to put text in the file. If you want to save just enter escape followed by :w, meaning you are saving the file with the name you have it to it, so for this example it would be example.txt. After you saved it, everything you type after pressing Esc is shown left down in the screen, simple type :q to quite it.
If you realise you do not really want to save the file you can just type :q! and if you were currently in the editing mode, meaning you were typing something, you just press Esc once followed by :q!.
So short summary:
vim example.txt (opens the editor if saved it will use the given name)
s (will enable edit mode, you can write stuff)
Esc (when you want to stop editing)
:w (save the file)
:q (quit the file, only usable when saved!)
:q! (discard the save and just exit the file)
you can use the following to create a file named "filename.py", insert "Hello World" into the file and then open the file,
$ echo "Hello World" > filename.py && open filename.py
On a Mac to create a lazytouch function to create and open a file in one line you have to edit .bashrc. You might have to first create it. Beware if you are a novice programmer. Some of these commands might require you to prepend sudo for permission to create and save. Enter these commands in terminal.
$ cd ~
$ touch .bashrc
$ open .bash_profile
Enter this profile in .bash_profile to check for .bashrc
# To get aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
Remember to save .bash_profile. Then in bash do this.
$ open .bashrc
Enter this text in the .bashrc
# .bashrc
# User specific aliases and functions
lazytouch() {
touch $1
open $1
}
Remember to save .bashrc
Now you can cd to any folder then create and open a file with one line.
$ lazytouch anything.really
you can use:
cat -> youNewFile.someExtension
Example:
cat -> myNewFile.txt
After you are done press Ctrl + d to save or Ctrl + c to abort (but in this case it's gonna save an empty file.
The redirection operator ( > ) will create the file if it doesn't already exists in your folder and you will be able to edit it right a way through the terminal.

iTerm2 get previous DIFFERENT command using up and down arrow keys

I found it irritating that if you run one command 5 times you have to press the arrow key 6 times to get the previous command. Is it some way to change this behavior?
iTerm2 Build 1.0.0.20111020
That's not a feature of iTerm but of your shell's history feature. If you use the default Bash you can put this into your ~/.bashrc:
export HISTCONTROL=ignoreboth
shopt -s histappend
# After each command, save and reload history
export PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND"
The first line will tell Bash to ignore duplicated and empty history entries. The second line will merge the history of multiple open sessions (e.g. in multiple tabs or windows). The thirs line will make sure that the history is preserved after each command.

Resources