Search code examples
shellenvironment-variablesfish

Setting Fish Environment Variable Only Once in Function


I am trying to use fish as my shell. When I login with LightDM, I want to start certain Xsession apps, but only when the shell in invoked at the outset by LightDM.

I have tried this in ~/.config/fish/config.fish:

###################################################################
# Start xsession applications, but only once.
if test -z "$XSESSION_STARTED"
  set -xg XSESSION_STARTED 'f'
end

if test "$XSESSION_STARTED" = 'f'
  xsession-apps
end

The function xsession-apps then starts all the apps in the background and sets the environment variable at the end like this:

set -xg XSESSION_STARTED "t"

But XSESSION_STARTED does not appear to get set to 't' and causes the xsession-apps function to get called every time, even when I start a new terminal within gnome-term.

What am I missing. Is there a better way to approach this?


Solution

  • even when I start a new terminal within gnome-term.

    That is to be expected. Global variables are set within that particular fish. If you start another fish, it won't have it (unless you start it inside that fish, because the variable is exported).

    There's a few ways to approach this:

    • Don't do it in config.fish at all - use the DE's autostart mechanism or at least ~/.xinitrc. This is the best and cleanest approach, and independent of your shell.

    • Use universal variables - these are stored persistently and shared for all fish sessions on the machine. The issue here is invalidating it - you need to unset the variable again once you logout/reboot, but if your machine crashed that wouldn't happen

    • Use a flag file on a tmpfs (i.e. in RAM) - this will be automatically invalidated if your machine stops, whatever the cause. You need to setup a tmpfs for it, though.