I'm new to bash and scripting.

I was thinking of writing an alias or a script so that every time I exit the command line, it will record my command history. Because I try a lot of new commands, and I would like to go back to the file and make comments to it, so I can learn better and not just try the commands and then forget them completely.

alias exit ="history > `date +%Y-%m-%d`.txt; exit"

but when I reload my bash, I get:

-bash: alias: exit: not found
-bash: alias: =history > 2015-09-22.txt; exit: not found

Why doesn't this work? Should I try to write a script with a while loop instead?

  • 3
    By the way, the error is caused by the fact that you have a space before the = in your alias command; it should be alias exit="history …". – Scott Sep 22 '15 at 21:42

Bash has a history file that you are probably looking for. Try vim ~/.bash_history or cat ~/.bash_history. It'll probably be what you are looking for. That is the history file location for redhat distros, might be located elsewhere for other distros... but the home directory makes sense for it :)

  • The history file is automatically read at bash startup (if it exists) so the commands from your previous session(s) can be reused with ! and seen with history. There are limits on the number of lines kept in memory and written to the history file, both defaulting to 1000 but changeable; if you exceed the limit(s) the oldest lines are discarded. – dave_thompson_085 Sep 23 '15 at 0:17

Trim the space before the equals sign:

alias exit="history > `date +%Y-%m-%d`.txt; exit"

Look at this. It looks like in bash you can set "traps" to be called when events happen. Try putting this is your .bashrc:

function show_history {
    history > `date +%Y-%m-%d`.txt
trap show_history EXIT

run help trap for more information.

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.