Replacing env variables in files without external tools

1 minute read

The following script recursively copies all files from /config-image directory to /config and replaces env variables inside the files.

1
2
3
find /config-image -name "*" -type f -print0 \
| xargs -0 -n1 sh -c \
'dest=$(echo "$0" | sed "s:/config-image:/config:"); mkdir -p $(dirname "$dest"); envsubst < "$0" > "$dest"'

For example, /config-image could contain next file:

1
2
3
4
5
6
<html>
  <head></head>
  <body>
    This is my home directory: $HOME
  </body>
</html>

The result of the script above would be next

1
2
3
4
5
6
<html>
  <head></head>
  <body>
    This is my home directory: /root
  </body>
</html>

All the replacement magic is done by envsubst but it took me a while to combine it with file copying and hierarchical file structure processing.

Script works in clean alpine setup with only gettext additional package installed.