Skip to content

Instantly share code, notes, and snippets.

@nikoheikkila
Last active February 7, 2025 22:05
Show Gist options
  • Save nikoheikkila/dd4357a178c8679411566ba2ca280fcc to your computer and use it in GitHub Desktop.
Save nikoheikkila/dd4357a178c8679411566ba2ca280fcc to your computer and use it in GitHub Desktop.
Fish Shell function for sourcing standard .env files

envsource

⚠️ NOTE (20.5.2023): I don't really use this function at all anymore since there are now tools such as Taskfile, which reads the .env file for me sparing me the need to pollute my session with environment variables.


I've been using Fish shell for years which is great and all, but one thing that has got me frustrated is using it with .env files.

When attempting to run source .env in a project, I usually encounter this problem:

.env (line 2): Unsupported use of '='. In fish, please use 'set KEY value'.
from sourcing file .env
source: Error while reading file '.env'

This is because Fish wants environment variables to be exported with syntax set -gx KEY value instead of export KEY=valuein Bash and ZSH.

So, I added the envsource command into my functions. Ideally, I wouldn't have to do this as many projects use dotenv or similar library to read environment variables. Then again, many projects are not quite there.

# Place this in your Fish functions folder to make it available immediately
# e.g. ~/.config/fish/functions/envsource.fish
#
# Usage: envsource <path/to/env>
function envsource
for line in (cat $argv | grep -v '^#')
set item (string split -m 1 '=' $line)
set -gx $item[1] $item[2]
echo "Exported key $item[1]"
end
end
@Real-Gecko
Copy link

A quick and dirty one-liner that works for straight-forward dotenv files using recent Fish versions:

. (sed 's/^/export /' .env | psub)

Fast and clean, thanks!

@berk-karaal
Copy link

I wrote a fish function for exporting dotenv files. I also added unexporting (unload) feature and wrote tests to make sure it's working.

https://github.com/berk-karaal/loadenv.fish

@Real-Gecko
Copy link

I wrote a fish function for exporting dotenv files. I also added unexporting (unload) feature and wrote tests to make sure it's working.

https://github.com/berk-karaal/loadenv.fish

Great stuff!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment