How can I set an environment variable only for the duration of the script?

LinuxBashEnvironment Variables

Linux Problem Overview


On Linux (Ubuntu 11.04 (Natty Narwhal)) in Bash, is it possible to temporarily set an environment variable that will only be different from the normal variable for the duration of the script?

For example, in a shell script, making an application that saves to HOME portable by temporarily setting HOME to a folder in the present working directory, and then launching the application.

Linux Solutions


Solution 1 - Linux

VAR1=value1 VAR2=value2 myScript args ...

Solution 2 - Linux

env VAR=value myScript args ...

Solution 3 - Linux

Just put

export HOME=/blah/whatever

at the point in the script where you want the change to happen. Since each process has its own set of environment variables, this definition will automatically cease to have any significance when the script terminates (and with it the instance of bash that has a changed environment).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsuchipiView Question on Stackoverflow
Solution 1 - LinuxRockalliteView Answer on Stackoverflow
Solution 2 - Linuxglenn jackmanView Answer on Stackoverflow
Solution 3 - Linuxhmakholm left over MonicaView Answer on Stackoverflow