Setting env variables in /bin/bash


reading time 1 min

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

1
2
3
export FOO=value
./the_command
unset FOO

Problem: What if FOO was already set?

How about…

1
2
3
4
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…

1
( export FOO=value ; ./the_command )

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

How about…

1
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.

1
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!




Tom Limoncelli

Tom Limoncelli

Recent Posts


  1. Postcards for Democracy
  2. Mrs. Creiger Was Calm
  3. Pride Rocks – New Jersey
  4. Configuring iPhone/MacOS to sync contacts
  5. Three AI links everyone should visit

Archive


Categories


Tags


I agree that this website may store my data to personalize my journey in accordance with their Terms & conditions

Powered by Hugo | Theme - YesThatTheme © 2017 - 2025 Tom Limoncelli