2

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:

  • @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. – Chris Conover Sep 22 '15 at 19:34
  • Your bash example doesn't work for me; did you mean export $(cat foo | xargs)? – Zanchey Sep 22 '15 at 23:38
  • 1
    @zanchey: too many back and forth edits, I have updated the bash example to use the $ in $(cat foo | xargs) – Chris Conover Sep 23 '15 at 4:07
3

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
  • Why does it work from bash though? – Chris Conover Sep 23 '15 at 4:02
  • 1
    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 Sep 23 '15 at 4:26
2

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
    I merged the export function in 2.2.0 (with thanks to Rack Lin). – Zanchey Sep 22 '15 at 23:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.