“notify-send” 未与“rclone”一起运行(在启动脚本中使用时)

“notify-send” 未与“rclone”一起运行(在启动脚本中使用时)

我正在尝试在启动时运行以下脚本。只有当我从终端执行脚本或将其作为程序运行时,我才能看到通知。因此问题基本上是在启动管理器运行时。

脚本:

#!/bin/bash

# Error log file
ERROR_LOG_FILE="$HOME/onedrive_mount_error_log.txt"
OUTPUT_LOG_FILE="$HOME/script_output_log.txt"

# Redirect stdout and stderr to OUTPUT_LOG_FILE
exec > "$OUTPUT_LOG_FILE" 2>&1

# Check if rclone is installed
if ! command -v rclone &> /dev/null; then
    echo "rclone not found. Exiting script."
    exit 1
fi

# Mount OneDrive using rclone
rclone --vfs-cache-mode writes mount OneDrive: ~/OneDrive
if [ $? == 0 ] ; then
    # If mount is successful, send a notification
    /usr/bin/notify-send "OneDrive Connected" "Microsoft OneDrive successfully mounted."
else
    # If mount fails, log the error
    echo "Failed to mount OneDrive on $(date)" >> $ERROR_LOG_FILE
    /usr/bin/notify-send "OneDrive Connection Failed" "Rclone failed to mount OneDrive."
fi

我正在使用 Ubuntu 23.10

内容.confing/autostart/onedrive.sh.desktop

[Desktop Entry]
Type=Application
Exec=/home/ernesto/Documents/Scripts/test-message.sh
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
X-GNOME-Autostart-Delay=10
Name[en_US]=Autostart Test message
Name=Autostart Test message
Comment[en_US]=Autostart Test message
Comment=Sync Automatic

答案1

rclone如果在前台运行(你可能想检查一下--daemon选项)将在维持该挂载期间(实际上是整个挂载时间)阻止执行脚本中的连续行

一种方法是增加rclone命令的详细程度并解析其输出(您需要观察输出才能知道要查找什么,但我已经这样做了):

#!/bin/bash

rclone -vv --vfs-cache-mode writes mount OneDrive: ~/OneDrive |&
while read -r l
  do
    # If mounted:
    grep -q 'Mounting on' <<< "$l" && notify-send -i info -u critical "INFO: One Drive" "$l"
    # On error:
    grep -iq 'error' <<< "$l" && notify-send -i error -u critical "ERROR: One Drive" "$l"
    done

...确保这部分位于脚本的底部,否则它将阻止执行后续行。

注意其中有 Bash(和类似的 shell)特定的语法...如果使用 POSIX shell,那么您可能需要更改|&2>&1 |grep ... <<< "$l"更改为printf '%s\n' "$l" | grep ...

另一种方法是(虽然有点复杂):

#!/bin/bash

m="$(rclone --vfs-cache-mode writes mount OneDrive: ~/OneDrive --daemon 2>&1)"

if [ "$?" -eq 0 ]
  then
    while pgrep -f "rclone --vfs-cache-mode writes mount OneDrive:" &> /dev/null
      do
        findmnt "$HOME"/OneDrive &> /dev/null && notify-send -i info -u critical "INFO: One Drive" "OneDrive successfully mounted ...\n" && break
        done
  else
    notify-send -i error -u critical "ERROR: One Drive" "Failed to mount OneDrive ...\n\n${m}\n"
  fi

相关内容