Cron 和 bash 脚本显示不同的日志

Cron 和 bash 脚本显示不同的日志

我有一个简单的脚本来查找配对的蓝牙耳机,如下所示,并将其安排在 cron 中每分钟运行一次。当蓝牙耳机打开时,它会工作并连接到配对的蓝牙耳机,如果蓝牙设备按预期关闭,它会失败。为了调试 cron 调度程序,我在日志中捕获了脚本的日志。并且该日志仅添加 0 个 stdout,而不是 1 个 stderr。

脚本

#!/bin/bash

TIMESTAMP=`date "+%d-%m-%Y %H:%M:%S"`

#rfkill block bluetooth ---Use this to block bluetooth
bluetoothctl power on
if [ $? == 0 ]
then
    echo "$TIMESTAMP Bluetooth is started.Connectting to paired device"
    bluetoothctl connect 74:45:CE:97:90:72
    if [ $? == 1 ]
    then
        echo "$TIMESTAMP Failed to Connect Sony headset. Please check the headset availability"
        bluetoothctl power off
        echo "$TIMESTAMP Stopped the Bluetooth"
    else
        echo "$TIMESTAMP Connected to Sony Headset via Bluetooth"
    fi
fi

计划任务:

#To Connect Bluetooth automatically
* * * * * /home/xxxxx/Documents/Shell/scripts/bluetooth.sh >> /home/xxxxx/Documents/Shell/scripts/logs/bluetooth.log 2>&1

当我手动运行脚本时,它会根据连接捕获 stderr 和 stdout。

Changing power on succeeded
23-01-2022 22:12:59 Bluetooth is started.Connectting to paired device
Attempting to connect to 74:45:CE:97:90:72
Failed to connect: org.bluez.Error.Failed
1
23-01-2022 22:12:59 Connected to Sony Headset via Bluetooth
HP-Pavilion:~/Documents/Shell/scripts$

但是,无论连接如何,日志 /home/xxxxx/Documents/Shell/scripts/logs/bluetooth.log 始终会显示以下输出,表示连接成功。

23-01-2022 22:10:01 Bluetooth is started.Connectting to paired device
Attempting to connect to 74:45:CE:97:90:72
0
23-01-2022 22:10:01 Connected to Sony Headset via Bluetooth
23-01-2022 22:11:01 Bluetooth is started.Connectting to paired device
Attempting to connect to 74:45:CE:97:90:72
0
23-01-2022 22:11:01 Connected to Sony Headset via Bluetooth
23-01-2022 22:12:01 Bluetooth is started.Connectting to paired device
Attempting to connect to 74:45:CE:97:90:72
0
23-01-2022 22:12:01 Connected to Sony Headset via Bluetooth
23-01-2022 22:13:01 Bluetooth is started.Connectting to paired device
Attempting to connect to 74:45:CE:97:90:72
0
23-01-2022 22:13:01 Connected to Sony Headset via Bluetooth
23-01-2022 22:14:01 Bluetooth is started.Connectting to paired device
Attempting to connect to 74:45:CE:97:90:72
0
23-01-2022 22:14:01 Connected to Sony Headset via Bluetooth

有人能帮我解决一下为什么每当蓝牙未连接时 cron 的日志中没有错误吗?

答案1

首先,即使手动运行也没有得到预期的结果。设备连接失败,最终输出应该是“无法连接到索尼耳机”。

选项 1:问题出在“echo $?”上。删除此语句即可解决问题。

选项 2:echo $? 的计算结果始终为 0,因此 if [$? == 1 ] 始终返回 false 并执行 else 语句。

因此,只需偷偷地放入这样的变量即可。

蓝牙连接 74:45:CE:97:90:72 x=$? echo $x if [ $x == 1 ]

相关内容