0

Os: debian9.

touch /home/test/test.log

There is a simple function write-date in /etc/profile.

write-date(){
    date >>  /home/test/test.log
    }

Create a service running at reboot or shutdown.

vim  /etc/systemd/system/test.service  

[Unit]
Description=Run command at shutdown
Before=shutdown.target reboot.target

[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/bash  /home/test/test.sh

[Install]
WantedBy=multi-user.target

The simple function write-date in /home/test/test.sh.

vim  /home/test/test.sh
write-date

Enable the test.service.

sudo systemctl enable test.service

Reboot my pc and check log of test.service

sudo journalctl -u test
-- Logs begin at Thu 2018-02-01 00:03:59 HKT, end at Thu 2018-02-01 00:15:54 HKT. --
Feb 01 00:04:04 test systemd[1]: Starting Run command at shutdown...
Feb 01 00:04:05 test bash[438]: /home/test/test.sh: line 3: write-date: command not found
Feb 01 00:04:11 test systemd[1]: test.service: Main process exited, code=exited, status=127/n/a
Feb 01 00:04:11 test systemd[1]: Failed to start Run command at shutdown.
Feb 01 00:04:11 test systemd[1]: test.service: Unit entered failed state.
Feb 01 00:04:11 test systemd[1]: test.service: Failed with result 'exit-code'.

How to make the command in /etc/profile be found ?

cat -vet /home/test/test.sh
$
$
    write-date$
    $
$
scrapy
  • 333
  • From what you show, you have the function defined but never invoked. – DopeGhoti Jan 31 '18 at 16:39
  • @DopeGhoti That doesn't really explain the "command not found". However, I wonder if /home still exists at the point when the service is invoked? I don't know much about systemd, but /home might be unmounted at shutdown and reboot on some systems, I presume? – Kusalananda Jan 31 '18 at 16:43
  • 3
    There's two function definitions for write-date, one in /home/test/test.sh and one in /etc/profile, and as DopeGhoti said, you don't appear to be calling it. Also, /etc/profile is only (automatically) read for login shells, which a systemd-invoked script would not be. – Jeff Schaller Jan 31 '18 at 16:52
  • Two blank lines on the top. – scrapy Feb 01 '18 at 02:37
  • The content you showed with vim /home/test/test.sh and the one with cat are completely different, – muru Feb 01 '18 at 02:41
  • Sorry for my typo in /home/test/test.sh , i want /home/test/test.sh to call write-date function from /etc/profile,please try to open an account in debian9 and with my code above to check what happens in your pc. – scrapy Feb 01 '18 at 02:43

1 Answers1

0

You probably need to explicitly tell your service that it needs to source /etc/profile.

[Unit]
Description=Run command at shutdown
Before=shutdown.target reboot.target

[Service]
EnvironmentFile=-/etc/profile
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/bash  /home/test/test.sh

[Install]
WantedBy=multi-user.target

Note the EnvironmentFile line.

Tim Kennedy
  • 19,697