Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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?

like image 587
Alexey Starinsky Avatar asked Jul 02 '19 16:07

Alexey Starinsky


People also ask

How do I set an environment variable password?

To save passwords and secret keys in environment variables on Windows, you will need to open Advance System Setting. You can navigate to control panel > System and Security > System > Advanced system Settings . Now in Advance System Setting click on Environment Variables .

How do I set environment variables in bash?

The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.

Is it safe to put passwords in environment variables?

Passing a password in an environment variable is as safe as having the program read it from a file. Only processes running as the same user may read a process's environment, and these processes are allowed to read the same files anyway. Note that this is different from passing a password on the command line.


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 
like image 62
jottbe Avatar answered Jan 01 '23 23:01

jottbe


$ read -rs PASSWORD
$ export PASSWORD
like image 33
Christian Oudard Avatar answered Jan 01 '23 21:01

Christian Oudard