Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

See how three solutions work together to help your teams have the tools they need to deliver quality software quickly. Brought to you in partnership with CA Technologies

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:

schema_name=test

database_url=database.mydomain.com 

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"` 

or

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.

Discover how TDM Is Essential To Achieving Quality At Speed For Agile, DevOps, And Continuous Delivery. Brought to you in partnership with CA Technologies

Topics:
bash ,shell ,scripting ,agile ,code quality

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}