2

I'd like to export all variables used by a certain systemd service, and are specified in its unit file using EnvironmentFile.

E.g. foo.service :

[Service]
...
EnvronmentFile=/foo.env
EnvronmentFile=/bar.env

foo.env:

a=1
#b=2
c=3

So I've thought adding to my bashrc something like

set -a
grep EnvironmentFile /etc/systemd/system/foo.service | grep -v '^ *#' | cut -d'=' -f2 | xargs  -I {} bash -c 'source {};'
set +a

as specified in this answer.

Is there a more elegant solution?

1 Answer 1

1

This won't work at all because you're executing a new bash shell to do the 'source'

Try:

load_env() 
{
  local files=( $(egrep '^[ ]*EnvironmentFile' "$1" ) )
  local f 
  set -a
  for f in "${files[@]}"
  do
     .   "${f##*=}"   # this expression delete the EnvironmentFile= part
  done
  set +a
}

load_env /etc/systemd/system/foo.service
1
  • If I'm reading this correctly, it is using the source (.) feature of the shell to read and interpret the Systemd EnvironmentFiles (as did the question). But that file has different syntax than POSIX shell (particularly it doesn't require quoting around spaces), and often isn't compatible.
    – pavon
    Nov 29, 2022 at 18:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .