首页 > 解决方案 > 在 cron 中转义哈希 (#)

问题描述

以下行在 cron 中有效:

* * * * * /usr/bin/mosquitto_pub -h  test.mosquitto.org -p 1883 -u dragino -t /MyExample/Topic -m "GPING-GPING-4-GPING-GPING"

这个没有:

* * * * * /usr/bin/mosquitto_pub -h  test.mosquitto.org -p 1883 -u dragino -t /MyExample/Topic -m "GPING#GPING#4#GPING#GPING"

请注意,我将-字符更改#为消息内部。我知道#角色需要缩放,但是如何?\#没用。

标签: cronescaping

解决方案


这种说法是不正确的:

空白行、前导空格和制表符将被忽略。第一个非空白字符是 <pound-sign> ( #) 的行是注释,不会被处理。 请注意,注释不允许与 cron 命令位于同一行,因为它们被视为命令的一部分。 同样,注释不允许与环境变量设置在同一行。

资源:man 5 crontab

您可以使用以下方法轻松测试:

* * * * * echo "#" > ~/foo.txt

您的问题很可能与mosquitto_pub. 虽然不熟悉该主题,但似乎您的消息中只能有一个#,并且应该在最后。

另一种解决方案可能是创建一个脚本/path/to/run_cronscript.sh,其中包含:

#!/usr/bin/env bash

/usr/bin/mosquitto_pub -h  test.mosquitto.org -p 1883 -u dragino -t /MyExample/Topic -m "GPING#GPING#4#GPING#GPING"

并将您的 crontab 调整为:

* * * * * /path/to/run_cronscript.sh

推荐阅读