How to Read a Properties File in Linux Shell Scripting

In this lesson, we are going to see how to read a properties file properly in Linux Shell Scripting. Let’s give it a go…

We will have our properties file config.properties and the properties reader shell script file read_properties_file.sh in this example. Save these two files in the same working directory with the following contents;

1. Our properties file config.properties will hold values in a key-value pairs:

config.name=Mamun
config.work.hours=39.5
config.location=Ottawa

2. The read_properties_file.sh file has the actual property reader functions:

#!/bin/bash
FILE_NAME="config.properties"
#read the properties file and returns the value based on the key
function getPropVal {
    value= grep "${1}" ./$FILE_NAME|cut -d'=' -f2
	if [[ -z "$value" ]]; then
	   echo "Key not found"
	   exit 1
	fi
	echo $value
}

#Get the value with key
function testPropertyVal {
NAME=($(getPropVal 'config.name'))
echo $NAME
}

#Call the testPropertyVal function
testPropertyVal

Run the script:

$ ./read_properties_file.sh

Also see file manipulation and how to Find file in Linux . See complete examples in our GitHub repository.

Follow us on social media

Author