1

I have below property file in same directory.

cancellation.properties

Content:

TestData=My Name

My unix script is abc.sh

Content:

#!/bin/ksh
. ./cancellation.properties

echo  "Please enter data to read"

read data

echo $data

While running I give the value TestData.

I am getting output as "TestData".

But I want output as "My Name". What changes needs to be done here because key will be entered by user.

JNevill
  • 46,980
  • 4
  • 38
  • 63
user2187367
  • 35
  • 2
  • 7

4 Answers4

2

You could use awk to get this.

In place of your echo $data put:

awk -F"=" -v data=$data '$1==data{print $2}' cancellation.properties

Which says "Split each record in your cancellation.properties file by an equal sign. If the first field is the value in variable $data (which is the variable data in your awk script set by that -v flag since you can't use shell variables directly in awk) then output the second field.

Also, now that read your question more thoroughly, it looks like you are including your .properties file at the top of the script. This may not be the best answer for you if you wish to proceed. See @cyrus comment to your question where it's noted to quote your variable assignment.

JNevill
  • 46,980
  • 4
  • 38
  • 63
2
#!/bin/bash

. <(awk -F '=' '{print $1 "=\""$2"\""}' file)

echo  "Please enter data to read"
read data
echo "${!data}"

Output:

My Name
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • I used -- <(awk -F '=' '{print $1 "=\""$2"\""}' ./cancellation.properties) But this not working getting output as data. – user2187367 Dec 08 '17 at 23:31
0

If there's the possibility that you might want other configuration data read from a file, I'd suggest treating your properties file like a config rather than an embedded script, and putting your data into a structure dedicated to storing configuration. Like an array. Something like this might work:

#!/usr/bin/env bash

declare -A canprop=()

while IFS='=' read -r key value; do
    [[ $key = #* ]] && continue      # handle comments
    canprop[$key]="$value"
done < cancellation.properties

printf '> %s\n' "${canprop[TestData]}"

Note that this particular solution doesn't work if $key is repeated within the configuration file -- the last key read will "win". But it saves you the hassle of putting everything into your "main" namespace.

ghoti
  • 45,319
  • 8
  • 65
  • 104
0

When you don't need to store the variables, and only want to display the value, you can do like this:

read -p "Please enter data to read: " data
grep "^${data}=" ./cancellation.properties | cut -d"=" -f2-
Walter A
  • 19,067
  • 2
  • 23
  • 43