6

I would like to have a log of all command that are typed on the terminal.

I have check "script" but this generates a file with the commands and the responds all together. Is there a way to have the commands only?

1
  • Typed or ran? Ran: cat ~/.bash_history. Typed: echo use your memory.
    – Lekensteyn
    Jan 24, 2011 at 16:00

5 Answers 5

7

If you are using the defaullt shells all the commands are already logged to $HOME/.bash_history . There are several environment variables which affect the history keeping, you can read about those with:

info bash
Type: / HIST

If you want to apply the setting to all users edit /etc/profile.

Example:

export HISTFILESIZE=5000
7

Everything a user types into the terminal by hand is saved into ~/.bash_history, where ~ is shorthand for the currenly logged in user's home directory. Note also that files beginning with a . are hidden; in Nautilus, you can show them by hitting Ctrl+H.

Take a look at it by typing

cat .bash_history

To view your history, annotated with sequential numbers, type

history

You can execute commands you see there again by typing !2129, for example, which would execute command number 2129 as shown by the history command.

Note that the history command shows you up to the second logs, wheras .bash_history is only saved after you log off from the terminal.

Little piece of interesting information:

  • Commands that begin with a space are not saved to .bash_history. If you run a command like rm -R mydir/, you may want to prefix it with a space to prevent accidentally running it again by hitting the up-arrow.

As Joāo says, the size of the saved history can be controlled with export HISTFILESIZE=5000.

1
  • However important to remember that if shell terminates abnormally, for example, because of network problems, firewall changes or because it was killed, then no history is written. Feb 22, 2014 at 15:04
1

You can also use CTRL+R in the terminal to search your history.

  1. CTRL+R
  2. enter search terms (e.g. type 'sudo apt-get')
  3. press CTRL+R to cycle through each match
0

If you mean you want a log of all commands you run in an interactive shell, see BashFAQ 88 - How can I avoid losing any history lines?

0

I wrote a function for this:

function begin_install_log() {
if [ $# -eq 0 ]
then
    echo "No arguments supplied"
    HIST_NUM=""
else
    HIST_NUM=$(history|tail -n 1|awk '{ print $1  }')
    HIST_NUM=$((HIST_NUM + 2))
    OUTPUT_FILE=$HOME/environment/ansible/.install_cache/${1}
fi
}
function capture_install_log() {
if [ ! $HIST_NUM ]
then
    echo "run 'begin_install_log' first"
else
    history|grep -A999 $HIST_NUM|awk '{$1=""; print $0}' >> $OUTPUT_FILE
    HIST_NUM=""
fi

Usage:

$ begin_install_log some_file_name
$ blah
$ blah
$ blah
$ capture_install_log

You will of course have to change the OUTPUT_FILE variable to suit your needs.

Cheers!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .