Reputation: 1058
I'm newly writing a bash script. I have a configuration file that sets some variables:
environment_information.conf
SIT_SERVER_IP=xxx.xx.xx.xx
SIT_SERVER_PASSWORD=******
I read the conf file and try to echo with predefined keys
echo $SIT_SERVER_IP
echo $SIT_SERVER_PASSWORD
It is working fine without any problem. In my scenario, I will read the values when executing a shell script.
automation_script.sh
#!/bin/sh
. ./environment_information.conf
environment_name=$1"_SERVER_IP";
# test="${environment_prefix}"; # Error
test="${environment_name}";
echo "$.$test";
echo $SIT_SERVER_IP
I tried to get value from conf using input and some constant value:
$ ./automation_script.sh SIT
$.SIT_SERVER_IP
xxx.xx.xx.xx
$
It always prints SIT_SERVER_IP
string.
But I'm expecting value from conf file for this SIT_SERVER_IP
.
Upvotes: 1
Views: 78
Reputation: 753615
I think you're looking for indirect expansion (paragraph 4 of Shell parameter expansion):
test=${!environment_name}
This expands to the value of the variable whose name is held in $environment_name
.
Proof of concept script, loosely based on your code (automation_script.sh
):
: "${1:?}" # Check that a parameter (SIT) was passed.
#. ./environment_information.conf
SIT_SERVER_IP="192.10.29.31" # Surrogate for configuration file
SIT_SERVER_PASSWORD="secret" # Surrogate for configuration file
echo "SIT_SERVER_IP=${SIT_SERVER_IP}"
echo "SIT_SERVER_PASSWORD=${SIT_SERVER_PASSWORD}"
environment_name="${1}_SERVER_IP"
echo "${environment_name}"
echo "${environment_name}=${!environment_name}"
environment_name="${1}_SERVER_PASSWORD"
echo "${environment_name}"
echo "${environment_name}=${!environment_name}"
Output from running the script:
$ bash automation_script.sh SIT
SIT_SERVER_IP=192.10.29.31
SIT_SERVER_PASSWORD=secret
SIT_SERVER_IP
SIT_SERVER_IP=192.10.29.31
SIT_SERVER_PASSWORD
SIT_SERVER_PASSWORD=secret
$
With the environment_information.conf file from the updated question:
: "${1:?}"
. ./environment_information.conf
#SIT_SERVER_IP="192.10.29.31"
#SIT_SERVER_PASSWORD="secret"
echo "SIT_SERVER_IP=${SIT_SERVER_IP}"
echo "SIT_SERVER_PASSWORD=${SIT_SERVER_PASSWORD}"
environment_name="${1}_SERVER_IP"
echo "${environment_name}"
echo "${environment_name}=${!environment_name}"
environment_name="${1}_SERVER_PASSWORD"
echo "${environment_name}"
echo "${environment_name}=${!environment_name}"
Running that yields:
$ bash automation_script.sh SIT
SIT_SERVER_IP=xxx.xx.xx.xx
SIT_SERVER_PASSWORD=******
SIT_SERVER_IP
SIT_SERVER_IP=xxx.xx.xx.xx
SIT_SERVER_PASSWORD
SIT_SERVER_PASSWORD=******
$
Upvotes: 3