how to parse a config file (*.conf) in shell script?

app-config, readfile, sh, shell

Solution

I'd do this:

pw=$(awk '/^password/{print $3}' app.conf)

user=$(awk '/^user/{print $3}' app.conf)


echo $pw
root123

echo $user
root

The `$()` sets the variable `pw` to the output of the command inside. The command inside looks through your app.conf file for a line starting `password` and then prints the 3rd field in that line.

EDITED

If you are going to parse a bunch of values out of your config file, I would make a variable for the config file name:

CONFIG=app.conf
pw=$(awk '/^password/{print $3}' "${CONFIG}")
user=$(awk '/^user/{print $3}' "${CONFIG}")

Here's how to do the two different ports... by setting a flag to 1 when you come to the right section and exiting when you find the port.

mport=$(awk '/^\[MySQL\]/{f=1} f==1&&/^port/{print $3;exit}' "${CONFIG}")
sport=$(awk '/^\[Server\]/{f=1} f==1&&/^port/{print $3;exit}' "${CONFIG}")

Problem

I am new to shell script. I have a file `app.conf` as : ``` [MySql] user = root password = root123 domain = localhost database = db_name port = 3306 [Logs] level = logging.DEBUG [Server] port = 8080 ``` I want to parse this file in shell script and want to extract mysql credentials from the same. How can I achieve that?

Original source