Kurt Peek
Kurt Peek

Reputation: 57431

How to set an environment variable for just one command in the Fish shell?

I have an environment variable GO111MODULE which is set to on in my ~/.config/fish/config.fish:

> echo $GO111MODULE
on

Following https://fishshell.com/docs/2.2/faq.html#faq-single-env, I would like to set it to off for a single command. As a sanity check I tried the echo command like so:

> env GO111MODULE=off echo $GO111MODULE
on

However, I notice that this is printing on instead of off as I would expect. Can anyone explain why this is not working?

Upvotes: 6

Views: 4562

Answers (2)

Sergei G
Sergei G

Reputation: 1690

Alternative:

 set -lx GO111MODULE off; echo $GO111MODULE
 echo $GO111MODULE

Sets local environment variable and unfortunately retains it for this session, which might not be what you want.

Upvotes: 0

Chris Dodd
Chris Dodd

Reputation: 126203

When you enter the command

env GO111MODULE=off echo $GO111MODULE

the variable $GO111MODULE is substituted immediately (in the current context) before env ever runs or gets a chance to set the variable. So env just sees GO111MODULE=off echo on as its arguments.

In order to see the effect of the environment change, you need to arrange to do the envvar lookup after env has set it. So something like:

env GO111MODULE=off sh -c 'echo $GO111MODULE'

will show the changed variable -- the single ' around it will prevent the current shell from expanding the var, so env will get 4 arguments: GO111MODULE=off sh -c and echo $GO111MODULE. It will then invoke sh with two args, which will in turn exapnd the variable and run echo with a single off arg.

Upvotes: 17

Related Questions