DEV Community

Discussion on: September 9th, 2021: What did you learn this week?

Collapse
 
vonheikemen profile image
Heiker • Edited

I learned about envsubst. I wish I knew about this before. This utility can substitute environment variables in a string that come from stdin.

I don't have many use cases for this but I think it would be very useful in config files that I share across multiple machines.

Quick example. Somewhere in a github repo I have a file called .npmrc, which I copy to any new machine I get. Inside that file I have this.

prefix=/absolute/path/to/npm/packages
Enter fullscreen mode Exit fullscreen mode

I don't like it, I want to replace that absolute path with this.

prefix=$XDG_CONFIG_HOME/npm/packages
Enter fullscreen mode Exit fullscreen mode

So, what I can do is create a template file and then create .npmrc from that.

envsubst < ~/templates/npmrc > ~/.npmrc
Enter fullscreen mode Exit fullscreen mode

The result on linux should be this:

prefix=/home/user/.config/npm/packages
Enter fullscreen mode Exit fullscreen mode

And if I wanted, I think I could use curl to fetch the content of the file and then pipe it to envsubst. So technically I don't even need the template in my filesystem.

EDIT: Yes, curl works like a charm.

curl -s "https://raw.githubusercontent.com/<my-user>/<some-repo>/main/npmrc" \
  | envsubst > ~/.npmrc
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nickytonline profile image
Nick Taylor

Nice!

A kangaroo playing an electric guitar