I have following command to clear last entry of bash history(terminal history/command-line history). My Ubuntu 14.04 Trusty Tahr.

sed -i '$d' ~/.bash_history

But I want to keep last 1,2...n entries and delete the rest, how can I achieve that ?

Can be with sed/history/awk or any other command, no problem as far as the requirements are met.

  • sed -i '1,10!d' ~/.bash_history replace 10 with whatever you want to count up to. – 123 Oct 3 '16 at 13:06

If you want to keep the last N lines, use tail (for example, the last 20 lines):

tail -n 20 "$HISTFILE" > ff && mv ff "$HISTFILE"

I'm using the HISTFILE variable since this will always point to your history file, even if you've changed its name.

| improve this answer | |
  • But when I run your command, I get error cannot open ‘/home/<user>/.bash_history’ for reading: No such file or directory. Why so ? echo "$HISTFILE" gives /home/user/.bash_history so path is correct. Also can this same thing be done with sed command ? – Vicky Dev Oct 4 '16 at 4:35
  • @VickyDev what do you get for ls -l "$HISTFILE"? It sounds like you don't have one. As for sed, no, not really. AFAIK there's no way for sed to count from the end of the file. You could reverse the file, take the top few lines and reverse it again (tac "$HISTFILE" | sed -n '1,10p' | tac > ff && mv ff "$HISTFILE" but that seems way too complicated. – terdon Oct 4 '16 at 8:05
  • As I said the path and vatiable are correct, also I get -rw------- 1 ubuntu ubuntu 0 Oct 4 10:44 /home/ubuntu/.bash_history for ls -l $HISTFILE but that doesn't work with tail command you gave in asnwer. It says /home/ubuntu/.bash_history’ for reading: No such file or directory. Oh didn't know tac(reverse of cat) was also there, thanks for that. – Vicky Dev Oct 4 '16 at 9:10
  • @VickyDev that doesn't really make sense. The error you show means that the file doesn't exist. However, your ls shows the file does exist (but is empty). Something very strange is going on here. Come into /dev/chat and ping me if you want to debug it further. – terdon Oct 4 '16 at 9:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.