我无法在 ubuntu 20.04 中保留 bash 脚本

I can't keep a bash script alive in ubuntu 20.04

我发现并稍微修改了以下脚本,它监视 notify-send 通知并将它们转储到文件中。

#!/bin/bash

logfile=

dbus-monitor "interface='org.freedesktop.Notifications'" |\
 grep --line-buffered "string" |\
 grep --line-buffered -e method -e ":" -e '""' -e urgency -e notify -v |\
 grep --line-buffered '.*(?=string)|(?<=string).*' -oPi |\
 grep --line-buffered -v '^\s*$' |\
 ts |\
 xargs -I '{}' -d '\n' echo -e {} >> $logfile

如果我 运行 手动:

notifylog notifylog.txt

该进程继续工作了一段时间,但最终停止了。如果我将它添加到 crontab,如:

@reboot /path/to/file/notifylog /home/user/notifylog.txt

它执行一次然后停止(或者它持续 运行ning 很少)。

我什至尝试将它添加到启动应用程序中,例如:

/path/to/file/notifylog /home/user/notifylog.txt

结果相同。手动执行但不是从 crontab 或启动应用程序执行时以下工作:

#!/bin/bash

logfile='/home/user/notifylog.txt'
rm -f $logfile
touch $logfile

while true; do /path/to/file/notifylog $logfile && break;done

我通过以下步骤添加到 systemd:

sudo nano /lib/systemd/system/notifylog.service

然后我补充说:

[Unit]
Description=notify-send log

[Service]
ExecStart=/path/to/file/notifylog

[Install]
WantedBy=multi-user.target

然后:

sudo systemctl daemon-reload
sudo systemctl enable notifylog.service
sudo systemctl start notifylog.service
sudo systemctl status notifylog.service

最后一个给我:

● notifylog.service - notify-send log
     Loaded: loaded (/lib/systemd/system/notifylog.service; enabled; vendor preset: enabled)
     Active: inactive (dead) since Wed 2021-10-20 19:01:49 -03; 3min 52s ago
    Process: 364180 ExecStart=/path/to/file/notifylog (code=exited, status=0/SUCC>
   Main PID: 364180 (code=exited, status=0/SUCCESS)

oct 20 19:01:49 mymachine systemd[1]: Started notify-send log.
oct 20 19:01:49 mymachine notifylog[364186]: Failed to open connection to session bus: Unable to autolaunch a dbus-daemon without a $DISPLAY for X11
oct 20 19:01:49 mymachine systemd[1]: notifylog.service: Succeeded.

好像不是运行宁

为此我稍微修改了脚本:

#!/bin/bash

logfile='/home/user/notifylog.txt'
rm -f $logfile
touch $logfile

dbus-monitor "interface='org.freedesktop.Notifications'" |\
 grep --line-buffered "string" |\
 grep --line-buffered -e method -e ":" -e '""' -e urgency -e notify -v |\
 grep --line-buffered '.*(?=string)|(?<=string).*' -oPi |\
 grep --line-buffered -v '^\s*$' |\
 ts |\
 xargs -I '{}' -d '\n' echo -e {} >> $logfile

编辑:现在我通过以下步骤将其作为用户添加到 systemd

首先,将 .service 文件添加到 /home/user/.config/systemd/user。 然后执行:

sudo systemctl daemon-reload
systemctl --user enable notifylog.service
systemctl --user start notifylog.service
systemctl --user status notifylog.service

这会正确启动服务,但是如果我重新启动我的机器,

systemctl --user status notifylog.service

给我:

● notifylog.service - notify-send log
     Loaded: loaded (/home/user/.config/systemd/user/notifylog.service; enabled; vendor preset: enabled)
     Active: inactive (dead)

我现在缺少什么?

目前有效的是更改 WantedBy 部分:

[Unit]
Description=notify-send log

[Service]
ExecStart=/path/to/file/notifylog
Restart=always

[Install]
WantedBy=default.target