Bash Snippet: Reading Values From a Configuration File

DZone 's Guide to

Bash Snippet: Reading Values From a Configuration File

In this article, we tackle the problem of simplifying bash commands. Sound intriguing? Read to learn the answer this developer came up with!

· Agile Zone ·
Free Resource

Recently, I was developing a bash script. To make the script flexible and configurable, we decided to maintain some of the values required by the application, in a configuration file. If a change was needed, we only needed to edit the config file and not the script, making script maintenance easier.

To get values from the config file, I used 'grep' and 'cut', as follows:

 schema_name=`grep "schema_name" config.cfg | cut -d '=' -f 2`
 database_url=`grep "database_name" config.cfg | cut -d '=' -f 2`

While the contents of the config file were:



If we need to fetch a lot of values from the config file, this method becomes repetitive and can be error-prone. Hence, I encapsulated the grep and cut commands inside a function, making it easier to fetch values, as follows:

getValueFromConfig() {
    VALUE=`grep ${1} config.sys | cut -d '=' -f 2`

In the defined function, ${1} is the first parameter passed to the function and is used to pass the key, whose value is to be read from the config file.

The way to use this function is

schema_name=`getValueFromConfig "schema_name"` 


schema_name=$(getValueFromConfig "schema_name") 

In fact, it is also possible to further customize the function to parameterize the separator used in the config file, as well as the position of the value that needs to be fetched from the config file.

agile, bash, code quality, scripting, shell

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}