Bash – Keep Only Successful Commands in BASH History

bashcommand history

Sometimes I misunderstand the syntax of a command:

# mysql -d test
mysql: unknown option '-d'
# echo $?
2

I try again and get it right:

# mysql --database test
Welcome to the MySQL monitor.
mysql >
...

How do I prevent the first command, with error code different than 0, to enter the history?

Best Answer

I don't think you really want that. My usual workflow goes like this:

  • Type a command
  • Run it
  • Notice it failing
  • Press UP key
  • Edit the command
  • Run it again

Now, if the failed command weren't saved into history I couldn't get it easily back to fix and run again.