1

This question is similar to this one: Is it possible to print the content of the content of a variable with shell script? (indirect referencing)

In a file that is

a=${env1}is a good ${env2}
b=${env3}is a good ${env2}

I would like to show content of this file to:

a=tom is a good cat
b=jerry is a good mouse

I tried this:

tmp=`cat a.conf`
echo $tmp # environmental variables are not interpreted, and file format changed, hard to read
echo ${!tmp} # no ...

Besides, above idea is kinda detour.

Tiina
  • 145

1 Answers1

1

If you have a file that looks like this:

a=${env1} is a good ${env2}
b=${env3} is a good ${env4}

And you want to produce output with the variables substituted, you use the envsubst command, which is part of the gettext package. Assuming the above is in example.txt.in, we could run:

env1=tom env2=cat env3=jerry env4=mouse envsubst < example.txt.in

And get as output:

a=tom is a good cat
b=jerry is a good mouse

If ensubst isn't available, you could do something like:

#!/bin/sh

tmpfile=$(mktemp scriptXXXXXX) trap 'rm -f $tmpfile' EXIT

cat > "$tmpfile" <<END_OUTSIDE cat <<END_INSIDE $(cat) END_INSIDE END_OUTSIDE

sh "$tmpfile"

Name the script something like envsubst.sh, and run it similarly to the previous example:

env1=tom env2=cat env3=jerry env4=mouse sh envsubst.sh < example.txt.in

larsks
  • 34,737
  • ./a.sh < file ;) Mostly that script works, except that it seems to miss default value when environment variable is missing, like this ${env1:dog} would be interpreted as dog when env1 is missing in printenv – Tiina Sep 15 '22 at 06:26
  • @Tiina your shell syntax there is incorrect; you want ${env1:-dog}. – larsks Sep 15 '22 at 12:53