As in this question for Bash, I'd like to have a simple .env file or similar that I can read into the Nushell environment. While I'll typically use this for API keys, to simply re-use the same example from that question:
MINIENTREGA_FECHALIMITE="2011-03-31"
MINIENTREGA_FICHEROS="informe.txt programa.c"
MINIENTREGA_DESTINO="./destino/entrega-prac1"
Of course, Nushell is not POSIX, so none of those answers will work.
The Nushell syntax for setting an environment variable is:
$env.foo = "value"
And while it's possible to source-env a file that modifies the environment, that file needs to be a valid Nu script, which the .env is not.
I'd like to keep the structure of the file "standard" so that it can be used with other shells and tools, but how can I use it to set environment variables in Nushell?
Took me a few tries to get right, so throwing this out in case it helps others (and so I can find it easily in the future). I found two ways to do this in Nushell.
Treat as a TOML file
The file format as it stands is a valid TOML file, and Nushell has built in support for TOML as structured data. As a result, we can easily read it with:
And from there, since the result is a Nushell record,
load-envcan be used to load it into the environment:TOML also supports comments, so you can have a valid (Bash) commented file as well and
from tomlwill ignore them.The caveats are that the file must be valid TOML, including quotes.
Or load it through Bash first
Fair warning: I know this seems really hacky, but I've been using this method successfully for a few years now on the Fish shell (also not POSIX) to process Bash scripts, and it also works for this modified use-case on Nushell.
With credit to this great answer on the Bash version of this question:
This:
execs Bash (replacing the current Nushell)sources the .envexecs Nushell, replacing the previous BashSince the variables were exported from Bash, they'll now be available in Nu.