brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: systemctl --user import-environment hands chosen variables to user services

Unit files
~/tips/tip-systemd-user-import-environment

systemctl --user import-environment VAR1 VAR2

Copies named variables from your shell into the user service manager's environment.

User services don’t start from your shell, so a variable you exported in a terminal is invisible to them. That’s the usual reason a service works when you run it by hand and fails under systemctl --user.

systemctl --user import-environment VAR1 VAR2

The systemctl man page describes it as importing one or more environment variables set on the client into the systemd manager environment block. With names given, the values from your current shell are copied across. Services started afterwards by your user manager get them.

export MY_API_URL=https://example.org
systemctl --user import-environment MY_API_URL
systemctl --user show-environment | grep MY_API_URL

The last line prints the variable from the manager’s environment block, so you can see that it landed. systemctl --user set-environment MY_API_URL=https://example.org does the same job when you want to give the value directly instead of reading it from the shell, and unset-environment removes a variable again.

I’d always list names. The man page says that calling import-environment with no arguments, which imports everything the systemctl process inherited, is deprecated, because a shell sets dozens of variables that only make sense locally and are confusing to other processes. Also, with names given, an invalid name or value raises an error.

Caveats: the man page says unset-environment cannot remove variables defined in the service manager configuration files or by generators. The man page also says show-environment doesn’t display per-unit variables, which are added when a unit process is forked. This was written from the documentation and was not run on a live user session.

Further reading: systemctl(1) man page

More Unit files tips [Service] sudo mkdir -p /etc/systemd/system/service.d [Service] [Service] [Service] All Unit files tips (28) All topics

Link