Bash – What ‘history’ command is used to display the contents of a bash history file besides ‘.bash_history’

bashcommand history

When doing some installations I change the 'HISTFILE' variable to a different file to record the commands used. Now I want to use the history command to display them just like with the history command which defaults to using the .bash_history file.

What option should be passed to the history command? When I try history ~/.history.d/alternate_historyI get the error message

-bash: history: /home/vfclists/.history.d/alternate_history: numeric argument required.

The man help lists some options which appear to make some changes to other history files I don't want.

Best Answer

The history command never operates on a file, only on its in-memory history list. You can only read (r), write (-w), and append (-a) that list to or from a file, and then access or manipulate the in-memory list. Reading from a file will replace or extend the history in your current shell session.

You can, however, spawn another shell and manipulate its history to run any command you want without affecting the history of your current shell:

bash -c 'history -cr file ; history'

or

( history -cr file ; history )

You can add any history options you want to the second history command in either case. If you'll be doing this a lot, you may want to define a function accepting the file as an argument and running the subshell version:

histfile() {
    ( history -cr "$1" ; history )
}

If you're interested in displaying saved timestamps, you'll also need to set HISTTIMEFORMAT. If you're using a subshell, and you get timestamps in your host shell, that should be there automatically, but for the bash -c version or a script you'll need to set it:

bash -c 'history -cr file ; HISTTIMEFORMAT="%Y%m%d%H%I%S " history'

You can also export the variable from the parent shell.

Related Question