how to set environment variables in fish shell

ShellFish

Shell Problem Overview


Can someone please tell me what's the correct way to set a bunch of environment variables in the fish shell?

In my .config/fish/config.fish file, I have a function to setup my environment variables like so

function setTESTENV
      set -x BROKER_IP '10.14.16.216'
      set -x USERNAME 'foo'
      set -x USERPASS 'bar'
end 

when I type from the command prompt setTESTENV and do a env in the command line, I don't see these information.

Shell Solutions


Solution 1 - Shell

Use Universal Variables

If the variable has to be shared between all the current user Fish instances on the current computer and preserved across restarts of the shell you can set them using -U or --universal. For example:

set -Ux FOO bar

Using set with -g or --global doesn't set the variable persistently between shell instances.


Note:

Do not append to universal variables in config.fish file, because these variables will then get longer with each new shell instance. Instead, simply run set -Ux once at the command line.

Universal variables will be stored in the file ~/.config/fish/fish_variables as of Fish 3.0. In prior releases, it was ~/.config/fish/fishd.MACHINE_ID, where MACHINE_ID was typically the MAC address.

Solution 2 - Shell

The variables you are declaring are keep in a local scope inside your function.

Use:

set -g -x

Here "g" is for global.

Solution 3 - Shell

another option is to run:

export (cat env_file.txt |xargs -L 1)

where env_file.txt contains rows of the format VAR=VALUE

this has the benefit of keeping the variables in a format supported by other shells and tools

Solution 4 - Shell

Environment Variables in Fish

I would like to add that, while @JosEduSol's answer is not incorrect and does help solve the OP problem, -g is only setting the scope to be global, while -x is causing the specified environment variable to be exported to child processes.

The reason the above fails, is because @cfpete is setting the env vars inside a function and the default scope will be local to that function.

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
QuestioncfpeteView Question on Stackoverflow
Solution 1 - ShellPaolo MorettiView Answer on Stackoverflow
Solution 2 - ShellJosEduSolView Answer on Stackoverflow
Solution 3 - ShellOphir YoktanView Answer on Stackoverflow
Solution 4 - ShellJorge BucaranView Answer on Stackoverflow