我无法在 ubuntu 20.04 中保持 bash 脚本存活



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

#!/bin/bash
logfile=$1
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

它执行一次,然后停止(或者它最后运行很少)。

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

/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