0

Hi i am an odd scenario

if i send below command manually in terminal it works well

root@VPRT:/home/root# mosquitto_pub -h localhost -p 1883 -q 1 -d -t test -i localClientID -m '2020-07-14 15:03:27'

But same when sent from the Bash script I get error

Error: Unknown option '15:03:27''.

my shell script is :

#!/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

if I send the same command that is PRINTED from the script it works but from the shell I get error. error only occurs with date format. if I send any other text from script it works. if I add the space between the date and time I get error.

i am confused as the same date with space works if manually sent

hardillb
  • 54,545
  • 11
  • 67
  • 105
  • 2
    It looks iike your `'` are not `'`. No, `${mystring}` is wrong, it undergoes wordsplitting and is splitted on spaces. Use bash arrays. – KamilCuk Jul 14 '20 at 11:05
  • Or better yet, don't store the command in a variable at all, just execute it directly. See ["Why does shell ignore quotes in arguments passed to it through variables?"](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quotes-in-arguments-passed-to-it-through-variables) and [BashFAQ #50: "I'm trying to put a command in a variable, but the complex cases always fail!"](http://mywiki.wooledge.org/BashFAQ/050) – Gordon Davisson Jul 14 '20 at 16:36
  • @GordonDavisson, thing is i uploaded the simplified script as demo. i need to add time stamp to some data I have. so I concatenate the data and send it with date and time. so I use variable. – Feroze Mohamed Jul 16 '20 at 05:40
  • 1
    @FerozeMohamed 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 Jul 16 '20 at 07:04
  • @GordonDavisson Thank you , will try that – Feroze Mohamed Jul 16 '20 at 16:21
  • @GordonDavisson It works. WOW. thank you – Feroze Mohamed Jul 16 '20 at 16:27

1 Answers1

0

As suggested by @Gordon Davisson, it worked.

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