suchipi
suchipi

Reputation: 1971

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

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.

Upvotes: 197

Views: 177292

Answers (4)

zhao Wang
zhao Wang

Reputation: 21

enter image description here We can use command env to alter environments or just use a simple augment method as bash mannual recording

The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described in Shell Parameters. These assignment statements affect only the environment seen by that command.

From Bash mannual

Upvotes: 1

hmakholm left over Monica
hmakholm left over Monica

Reputation: 23342

WARNING --- READ THE COMMENTS.


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

Upvotes: 46

Rockallite
Rockallite

Reputation: 16935

VAR1=value1 VAR2=value2 myScript args ...

Upvotes: 183

glenn jackman
glenn jackman

Reputation: 247012

env VAR=value myScript args ...

Upvotes: 83

Related Questions