Interview Questions

Shell Script - How to read Property File using Shell Script

In this Shell Script section, Let us see how to fetch the Value from the Property File based on the Key.

Consider a Property File named "Test.prop" which is of the below format,

Test.prop

Name=Admin
Age=24
Occupation=Farmer

In the above Property file, Let us fetch the Value for the key (i.e., Name) and display the same. Go through the below script file once so that we can discuss the steps involved.

ReadProperty.sh

# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

# Script used to read Property File
FILE_NAME=Test.prop

# Key in Property File
key="Name"

# Variable to hold the Property Value
prop_value=""

getProperty()
{
        prop_key=$1
        prop_value=`cat ${FILE_NAME} | grep ${prop_key} | cut -d'=' -f2`
}

getProperty ${key}
echo "Key = ${key} ; Value = " ${prop_value}

In the above script, the method getProperty() method identifies the Property file to be read and fetches the entire row using the Key (i.e., Name). Now it will have the complete string i.e., Name=Admin.

Our motto is to fetch only the Value i.e., Admin. Hence using the cut command, the Value is separated using the delimiter ("=").

Though its a simple one, hope this will be useful for beginners!