How can I set environment variable for just one command in fish shell?

Solution 1:

Don't see why this shouldn't work: env EDITOR=vim crontab -e
That bypasses the shell completely.

Solution 2:

begin; set -lx EDITOR vim; crontab -e; end

Solution 3:

That is from the Documentation

SOME_VAR=1 command produces an error: Unknown command "SOME_VAR=1".

Use the env command.

env SOME_VAR=1 command

You can also declare a local variable in a block and that would not bypass the shell

begin
  set -lx SOME_VAR 1
  command
end

Solution 4:

depending on a definition of be function, this can fail

begin
  set -lx RAILS_ENV staging
  be rails r "p ENV['RAILS_ENV']"
end

In order for it to work:

function be --description 'Runs bundle exec' --no-scope-shadowing
  bundle exec $argv
end

Please, see the explanation of --no-scope-shadowing option

-S or --no-scope-shadowing allows the function to access the variables of calling functions. Normally, any variables inside the function that have the same name as variables from the calling function are "shadowed", and their contents is independent of the calling function.

Tags:

Shell

Fish