BASH - 如果时间 'space' 我的代码有问题,Mosquitto_pub 命令会抛出错误
BASH - Mosquitto_pub command throws error if time has 'space' something is wrong with me code
嗨,我是一个奇怪的场景
如果我在终端中手动发送以下命令,效果很好
root@VPRT:/home/root# mosquitto_pub -h localhost -p 1883 -q 1 -d -t test -i localClientID -m '2020-07-14 15:03:27'
但是当从 Bash 脚本发送时我得到错误
Error: Unknown option '15:03:27''.
我的 shell 脚本是:
#!/bin/bash
mqttcmd="mosquitto_pub -h localhost -p 1883 -q 1 -d -t test -i localClientID -m "
dateformat="%Y-%m-%d %H:%M:%S"
function my_date {
date "+${dateformat}"
}
while true; do
today=$(my_date)
echo "today : " $today
mystring="$mqttcmd"
mystring+="'"
mystring+="$today"
mystring+="'"
#print
echo ${mystring}
#publish
${mystring}
sleep 5
done
如果我发送从脚本打印的相同命令,它可以工作,但从 shell 我收到错误。
错误仅发生在日期格式上。如果我从脚本发送任何其他文本,它就可以工作。如果我在日期和时间之间添加 space 我会出错。
我很困惑,因为与 space 相同的日期如果手动发送就可以工作
正如@Gordon Davisson 所建议的那样,它奏效了。
You can use variables as part of commands (but put double-quotes around them), but don't put commands in variables. For your script, remove the mqttcmd and mystring variables, and just run mosquitto_pub -h localhost -p 1883 -q 1 -d -t test -i localClientID -m "$today" – Gordon Davisson
嗨,我是一个奇怪的场景
如果我在终端中手动发送以下命令,效果很好
root@VPRT:/home/root# mosquitto_pub -h localhost -p 1883 -q 1 -d -t test -i localClientID -m '2020-07-14 15:03:27'
但是当从 Bash 脚本发送时我得到错误
Error: Unknown option '15:03:27''.
我的 shell 脚本是:
#!/bin/bash
mqttcmd="mosquitto_pub -h localhost -p 1883 -q 1 -d -t test -i localClientID -m "
dateformat="%Y-%m-%d %H:%M:%S"
function my_date {
date "+${dateformat}"
}
while true; do
today=$(my_date)
echo "today : " $today
mystring="$mqttcmd"
mystring+="'"
mystring+="$today"
mystring+="'"
#print
echo ${mystring}
#publish
${mystring}
sleep 5
done
如果我发送从脚本打印的相同命令,它可以工作,但从 shell 我收到错误。 错误仅发生在日期格式上。如果我从脚本发送任何其他文本,它就可以工作。如果我在日期和时间之间添加 space 我会出错。
我很困惑,因为与 space 相同的日期如果手动发送就可以工作
正如@Gordon Davisson 所建议的那样,它奏效了。
You can use variables as part of commands (but put double-quotes around them), but don't put commands in variables. For your script, remove the mqttcmd and mystring variables, and just run mosquitto_pub -h localhost -p 1883 -q 1 -d -t test -i localClientID -m "$today" – Gordon Davisson