Lovingly hand-crafted in small batches just for you by me.

May 26, 2020 - 1 minute read - Comments - technology

Setting env variables in /bin/bash

If you want to set an env variable in bash for only 1 command, here’s some bad ways to do it:

export FOO=value
unset FOO

Problem: What if FOO was already set?

How about…

export FOO=value

Problem: Ok, now you revert FOO to its original value, but what a pain in the ass!

How about…

( export FOO=value ; ./the_command )

Well, that certainly works. () creates a new environment by calling fork() but that’s pretty heavyweight.

How about…

FOO=value ./the_command


Yes, that sets FOO, exports it, and only sets it for the execution of one command. You can even set more variables.

FOO=value BAR=otherthing ./the_command

This is the second least known feature of bash. I’ll write about what I think is the least know feature in my next blog post.