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!
Join the DZone community and get the full member experience.
Join For FreeRecently, 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.
Opinions expressed by DZone contributors are their own.
Comments