3

Is it possible to set environment variables with export in Fish Shell? I am working on a project that configures variables this way and it does not make sense to maintain a separate configuration file just for fish.

Consider this example in bash:

echo -e "foo=1\nfoobar=2\n" > foo; export $(cat foo | xargs); env | grep foo

   foo=1
   foobar=2

In fish shell, it appears that it will only set a single variable, and only if there is one variable in the file:

~ $ echo -e "foo=3\nfoobar=4" > foo; export (cat foo | xargs); env | grep foo

~ $ echo -e "foo=3" > foo; export (cat foo | xargs); env | grep foo

   foo=3

Is this just a flaw / omission in the Fish implementation of export?

This question is similar to but different from these other two posts:

3
  • @StéphaneChazelas: I realize that fish uses set, but given that export is a builtin in bash, and there is no binary to fallback to, where else would it be coming from? My example above showed that it worked for a single argument but not two. If not for this detail, fish could be used in more teams that primarily use bash. Commented Sep 22, 2015 at 19:34
  • Your bash example doesn't work for me; did you mean export $(cat foo | xargs)?
    – Zanchey
    Commented Sep 22, 2015 at 23:38
  • 1
    @zanchey: too many back and forth edits, I have updated the bash example to use the $ in $(cat foo | xargs) Commented Sep 23, 2015 at 4:07

2 Answers 2

5

Your example almost works perfectly - it's not export that's the problem, but the use of xargs.

Try:

echo -e "foo=3\nfoobar=4" > .env; export (cat .env);  env | grep foo

The reason is that a command substitution separates arguments on newlines, and xargs removes them:

> count (cat .env | xargs)
1
> count (cat .env)
2
2
  • Why does it work from bash though? Commented Sep 23, 2015 at 4:02
  • 2
    Bash separates command substitution arguments on space, not newline. Newline isn't perfect - you can embed newlines in file names - but it's a lot better. Otherwise you get funny problems with files with embedded spaces.
    – Zanchey
    Commented Sep 23, 2015 at 4:26
3

In fish, I'd expect you to get an error for export:

$ echo -e "foo=1\nfoobar=2\n" > foo; export (cat foo | xargs);  env | grep foo
bash: --: command not found...
fish: echo -e "foo=1\nfoobar=2\n" > foo; export (cat foo | xargs);  env | grep foo
                                         ^

If you have a file with variable=value lines and you want to use that to set environment variables:

$ cat foo
foo=1
foobar=2

$ source (sed -rn 's/^([^=]+)=(.*)/set -x \1 \2/p' foo | psub)
$ set -x | grep foo
foo 1
foobar 2
1
  • 1
    I merged the export function in 2.2.0 (with thanks to Rack Lin).
    – Zanchey
    Commented Sep 22, 2015 at 23:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .