0

I am trying to read a value from my config file and substituting it in my other file named test.env.

config file has key and value pair as below:

SERVER_NAME=testserver
HOSTNAME=localhost

test.env file

echo "server name is ${SERVER_NAME}"
echo "Server is running on host ${HOSTNAME}"

Would it be possible to automatically assign a variable in test.env file.

Expected output will be as follows:

echo "server name is testserver"
echo "Server is running on host localhost"
Cyrus
  • 84,225
  • 14
  • 89
  • 153
user15566016
  • 33
  • 10
  • Which shell do you use? – Cyrus Feb 03 '22 at 11:29
  • I am using a bash shell – user15566016 Feb 03 '22 at 11:35
  • Are you trying to permantly modify `test.env`? Or print out its contents but with the variables substituted (based on config file)? – dan Feb 03 '22 at 12:32
  • Why don't you want to use `source`? – Cyrus Feb 03 '22 at 12:38
  • @dan Yes, I permanently want to modify the test.env file with actual contents from config file – user15566016 Feb 03 '22 at 13:09
  • @Cyrus Due to security reasons I am trying to avoid use of source – user15566016 Feb 03 '22 at 13:12
  • `source <(sed -E '/^(SERVER_NAME|HOSTNAME)=[a-zA-Z0-9]+$/!d' file)`? – Cyrus Feb 03 '22 at 13:31
  • The linked duplicate has an accepted answer where one of the branches does not use `source`. – Charles Duffy Feb 03 '22 at 15:54
  • That said, insofar as you care about security, I **strongly** recommend reading your variables into an associative array, not directly into environment variables. There are a _lot_ of environment variables where an attacker can leverage control of that variable's value into arbitrary code execution later (think `LD_PRELOAD`, `PATH`, or even variables that be eval'd by a shell during prompt formatting), so when you care about security, you should either put variables read from an untrusted source into an associative array or put a lowercase prefix on the front of their names – Charles Duffy Feb 03 '22 at 15:55
  • (a lowercase prefix because POSIX requires that standard-defined tools use only all-caps environment variables to modify their behavior, whereas names with lowercase characters are reserved for application use, and POSIX-compliant tools must not modify their behavior based on same -- see https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html) – Charles Duffy Feb 03 '22 at 15:57

0 Answers0