Set an environment variable (password) in a way its value is not saved to the bash history

Viewed 9476

When I login to MySQL as root I usually set MROOTPASS environment variable

export MROOTPASS=my-secret-password

and then do

mysql -u root -p$MROOTPASS

this eliminates the need to reenter the password each time I connect to MySQL as root, but obviously it is insecure because the password is saved to the bash history file. Is it possible to prevent the password from being saved?

2 Answers

You could just enter the variable using

read -s -p "Enter password:" MROOTPASS 

this way it also wouldn't appear anywhere without having to save it in a file. Instead you just have to enter it once. The -s option tells read not to echo the typed characters, so nobody can look it up while you type it.

Edit: long time after this answer was accepted some people stated, that this doesn't define system variables but shell variables. If you need your variable to be visible in a subshell, you just need to rexport the variable by adding the following line below the read statement (bash):

export MROOTPASS 
$ read -rs PASSWORD
$ export PASSWORD
Related