YesThatBlog.Com

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
./the_command
unset FOO

Problem: What if FOO was already set?

How about…

export REMEMBER_FOO="$FOO"
export FOO=value
./the_command
export FOO="$REMEMBER_FOO"

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

What???

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.

Enjoy!