Reputation: 23
If I have a given property file and a shell script. How do I store each and every key-value pair in a different variable?
For example if I read the property file thing.properties that consists of:
USERNAME = "Me"
PASSWORD = "Secret"
DB_NAME = "THINGDB"
How do I store each of these keys in its own variable within the shell script labeled thingUSERNAME, thingPASSWORD etc. (Variable name can be anything as long is it contains some semblance of the file and the key)
(Note this must be done in an sh file) Any input is appreciated
Upvotes: 0
Views: 820
Reputation: 2981
You can use eval
. Just be careful with this command though. It can be devastating. Unfortunately unlike bash
, sh
does not support declare
.
$ cat property.txt
USERNAME = "Me"
PASSWORD = "Secret"
DB_NAME = "THINGDB"
$ cat shell.sh
#!/bin/sh
while IFS= read -r line; do
key="${line%% =*}"
value="${line#*= }"
eval "$key"="$value" # For ash, dash, sh.
# declare "$key"="$value" # For bash, other shells.
done < property.txt
echo "username: $USERNAME"
echo "password: $PASSWORD"
echo "db_name: $DB_NAME"
$ ./shell.sh
username: Me
password: Secret
db_name: THINGDB
Upvotes: 1