Wednesday, July 16, 2014

Hide command from bash command line history

Linux is known as a very secure operating system. But, it is not going to save us if we voluntarily or unknowingly expose ourselves to unnecessary danger. For instance, a password-authenticated command may allow you to specify the password right on the command-line.

$ mysql -u root -pMyPassword

The command you just executed - with the mysql root password - gets recorded in the shell command history file. For bash, the history file is ~/.bash_history. This is not desirable for security.

$ tail ~/.bash_history ... mysql -u root -pMyPassword $

The most effective solution is to break the bad habit: don't enter any password on the command line. For the above example, make mysql prompt you for the password:

$ mysql -u root -p Enter password: mysql>

Failing that, you can mitigate the security risk by hiding a command from the command line history. Note: the technique below only works for the bash shell. It won't work for zsh, tcsh, etc. (If you do know the trick for these shells, please let us know through comments).

The bash trick is to enter one or more leading spaces before the actual command.

$ mysql -u root -pMyPassword

A leading blank. Just like that, and the command you enter won't be written into the command history file.


Anonymous said...

This is incorrect in a test on CentOS 5. Does not work.

What does work is unsetting the history file.


This command itself is also conviently not recorded.

This command works Linux & Solaris bash shells. It may work in others.

Master said...

or just fucking use ~/.my.cnf as a normal human being

Anonymous said...

or first switsh to 'sh', this 'sh' shell does not use a history file:

bash$ sh
$ mysql -u root -pMyPassword
$ exit

However, the calling of 'sh' is being recorded in the ~/.bash_history file