Bash history number not starting at 1?

5,302

Solution 1

From man bash:

   On startup, the history is initialized from the file named by the vari‐
   able HISTFILE (default ~/.bash_history).  The file named by  the  value
   of  HISTFILE  is  truncated,  if necessary, to contain no more than the
   number of lines specified by the value of HISTFILESIZE. [...] When an 
   interactive  shell  exits, the last $HISTSIZE lines are copied from the
   history list to $HISTFILE.

While that text is quite clear, let's play a bit by example (this is a deb system, but bash is bash).

My history status right now:

~$ set | grep HIST
HISTCONTROL=ignoredups:ignorespace
HISTFILE=/home/hmontoliu/.bash_history
HISTFILESIZE=2000
HISTSIZE=1000

Since HISTFILESIZE is 2000 and HISTSIZE is 1000 only the last 1000 lines of the HISTFILE are available so you can get the wrong impression that my history starts at 1000.

~$ history | head -1
 1000  if i=1; then echo $i; done

~$ history | wc -l
1000

But indeed the HISTFILE stores the last 2000 commands:

 ~$ wc -l $HISTFILE
2000 /home/hmontoliu/.bash_history

If you think that it is annoying you can equal the HISTSIZE and HISTFILESIZE

~$ echo "export HISTSIZE=$HISTFILESIZE" >> .bashrc
~$ bash -l
~$ history | head -1
    1  ls
~$ history | wc -l
2000
~$ set | grep HIST
HISTCONTROL=ignoredups:ignorespace
HISTFILE=/home/hmontoliu/.bash_history
HISTFILESIZE=2000
HISTSIZE=2000

A final hint: you should run help history to view the actions you can do with your history

Solution 2

The answer from hmontoliu is quite good, this is just a TL;DR version.

The bash history always picks up where you left off. It keeps a semi-permanent history of commands run in a file in your home directory. Every time you start a bash shell it loads this history file and you can scroll up to commands run in previous sessions. If you had 274 previous commands in history, your command history number on a new shell would start with 275.

The history file is truncated to a maximum length specified by the environment variable $HISTFILESIZE. You apparently have it truncated your history file to a maximum of 500 lines, so every new shell starts at 501. The previous history items are a collection of the last 500 items from previous shells.

Share:
5,302

Related videos on Youtube

Harsha
Author by

Harsha

Updated on September 18, 2022

Comments

  • Harsha
    Harsha over 1 year

    I was customizing my bash prompt (I'm on OS X 10.7) when I came across something strange. Within my prompt I included !, which should give me the history number. However the history number always starts out at 501, instead of 1. This is true even if I restart Terminal.

    I can't seem to find anything close to this, I was wondering if you guys could offer some insight.