How to change user for a bunch of systemd service files?

using sed:

sed -i 's/^User=Foo$/User=Bar/' /etc/systemd/service/myapp.*.service

Who says that you need to change the files at all? ☺

find /etc/systemd/service/ -maxdepth 1 -name 'myapp.*.service' |
while read -r i
do
    printf '[Service]\nUser=%s\n' 'Bar' > ${i}.d/change-user.conf
done

Getting the vanilla service definition back again is somewhat easier this way.

rm -- /etc/systemd/service/myapp.*.service.d/change-user.conf

Making these all one single file that applies across a whole bunch of services is of course just a simple exercise in the use of hard links.

install -d /etc/systemd/temp
printf '[Service]\nUser=%s\n' 'Bar' > /etc/systemd/temp/change-user.conf
find /etc/systemd/service/ -maxdepth 1 -name 'myapp.*.service' |
while read -r i
do
    ln /etc/systemd/temp/change-user.conf ${i}.d/change-user.conf
done

This is of course the official way to do this sort of thing with package-supplied and runtime-generated units, moreover. You are supposed not to change such unit files.

Further reading

  • Lennart Poettering (2013-10-07). systemd.unit. systemd manual pages. freedesktop.org.