Set environment variables for gnome on wayland and bash on virtual terminals (or ssh)

Systemd version 233 (March 2017) added support for setting environment variables in ~/.config/environment.d/*.conf. See the environment.d man page and the discussion that led to the feature on this preliminary PR and this final one.


This is the workaround that I use for the exact same problem:

Step 1

Create a script that sources ~/.profile and make that script executable. Let's call it /path/to/startup.sh. It could look something like this:

#!/bin/bash
. ~/.profile

Step 2

Create a desktop application to run the script. To do this you need to create a .desktop file and place it in ~/.local/share/applications (or /usr/share/applications if you want it to work for all users). Let's call it ~/.local/share/applications/startup.desktop. It could look something like this:

[Desktop Entry]
Name=Startup
Keywords=startup
Exec=/path/to/startup.sh
Type=Application

For more information on .desktop files see here.

Step 3

Log out. Log back in. You should now be able to search for your application in the applications menu.

Step 4

Set this application as a startup application. To do this I used the Gnome Tweak Tool and added my application to the list in the Startup Applications tab.

And that's it! You should now have your old functionality back whenever you log in. It also preserves the file structure intact, so, when the bug in Wayland gets fixed, all you need to do it remove the application from the startup application list, delete the two files and everything is back to normal.

Later edit

As @Guss points out in the comments, this workaround will not export environment variables because startup.sh is run in its own shell. So we need another workaround for those.

Reading from the GNOME documentation you can see that there are a few alternatives. The only one that I could get to work was to create a file in /usr/share/gdm/env.d/ and, in that file, place the variables to be exported. However, this means that the variables will be exported for all users so what I ended up doing is this:

Let's say we have two users, john and sally. For each of them create a file in /usr/share/gdm/env.d/, let's call them startup_john.env and startup_sally.env. In those files place the environment variables to be exported when they start a new GNOME session.

$ cat startup_john.env
VAR=1
$ cat startup_sally.env
VAR=2

At this point the problem is that both files will be loaded for both users. In order solve this we set the permission on each file such that only its owner may read its contents.

$ ls -l startup_john.env
-rw-r-----. 1 john john 4 Dec 27 15:17 startup_john.env
$ ls -l startup_sally.env
-rw-r-----. 1 sally sally 4 Dec 27 15:16 startup_sally.env

Not the most elegant solution, I agree, but, as far as I have tested, it seems to get the job done.