retrieve plaintext password from file using bash command

2.9k Views Asked by At

I want to read a value from a known file.

File is located at /root/.my.cnf and contains

[client]
password='PosftGlK2y'

I would like to return PosftGlK2y - ideally using a simple one liner command.

I have tried

cat /root/.my.cnf | grep password

which returns password='PosftGlK2y'

I am sure there is a better way.

2

There are 2 best solutions below

7
On

You can skip the cat and grep directly, and then pipe to awk with a ' delimiter.

grep password /root/.my.cnf | awk -F"'" '{print $2}'

Alternately, you can skip the grep altogether and just use awk to do the search and the extraction.

awk -F"'" '/^password=/{print $2}' /root/.my.cnf
0
On

You could use cut to split the line on the ' character:

grep password= /root/.my.cnf | cut -d "'" -f 2

returns

PosftGlK2y

The cut command splits a line on the delimiter (-d flag) and returns the column(s) specified by the f flag.