I am using systemd service for my script I need to set environment vaules from a home/user/.bashrc
source /home/user/.bashrc
not works in script and systemd seed don't support sourcing function.
Help me
Instead of trying to generate an EnvironmentFile, have a shell execute your startup scripts and then execute your command. This avoids steps that can introduce a mismatch (as between how env
stores your environment, and how the systemd EnvironmentFile
option loads it).
[Service]
Type=simple
User=user
Group=user
ExecStart=/bin/bash -l -c 'exec "$@"' _ your-command arg1 arg2 ...
Here, instead of using bash -l
to run a login shell, we explicitly source $0
, and pass /home/user/.bashrc
in that position.
[Service]
Type=simple
User=user
Group=user
ExecStart=/bin/bash -c '. "$0" && exec "$@"' /home/user/.bashrc your-command arg1 arg2 ...
.bashrc
files are generally intended for setting up interactive environments. This means that their settings are often not appropriate for services.EnvironmentFile
that you hand-audit for your service means you know exactly what the service is running with, and can configure it separately from the interactive environment. If you've hand-audited that EnvironmentFile to have the same meaning when executed by a shell, you could also run set -a; source /path/to/your-environment-file; set +a
in your .bashrc
to pull its environment variables in.EnvironmentFile
in a non-user-writable location like /etc/conf.d
is thus safer than a dotfile under that user's home directory.bash -l
is right and using a static EnvironmentFile file is wrong. There are variables that can be dynamically initialized by Bash's initialization scripts. Obviously you might suggest moving these dynamic initializations to systemd but that isn't always adaptable and practical.
Jan 7, 2022 at 16:18
ExecStart=/bin/bash -c '. "$0" && exec "$@" /home/user/.bashrc your-command arg1 arg2 ...'
"$@"
. In particular, when you do that, you don't have a $0
or a $@
because everything goes into the -c
argument to be run as a script. Indeed, I'm surprised it works at all -- I would have expected the . "$0"
to fail (on account of $0
not being set to the name of a source
able script), and consequently everything else to not be run at all.
Jun 21, 2022 at 17:21
.bashrc
rather than an EnvironmentFile?