-3

In bash script, I have a variable, say $date, that obtained string value from some other function, say the value of $date is 04 Feb 2020. I want to mosquitto_pub the value in $date, but it can't because mosquitto_pub expect no space after 04. I understand that I have to put the double quote around 04 Feb 2020 (as if $date='"04 Feb 2020"'), how to do it?

Thanks

bthoven
  • 15
  • 3
  • 1
    You don't include quotes in the variable. You just quote the parameter expansion. `date="04 Feb 2020"; some_command "$date"`. – chepner Feb 04 '20 at 15:25

2 Answers2

1

All you need to do is quote the parameter expansion. Given

date="04 Feb 2020"

a command line like

some_command $date

will pass 3 arguments (04, Feb, and 2020) to some_command after the shell applies word-splitting to the result of the parameter expansion.

To prevent the word-splitting, you simply need to quote the parameter expansion, not add literal quotes to the result.

some_command "$date"
chepner
  • 497,756
  • 71
  • 530
  • 681
0

Escape the double quote:

d="04 Feb 2010"; d2="\"$d\""; echo $d2
"04 Feb 2010"
JRFerguson
  • 7,426
  • 2
  • 32
  • 36
  • Thanks a lot. The double quote is there by your example; but mosquitto_pub still report "Error: Unknown option 'Feb'." Do you know what might cause this error? – bthoven Feb 04 '20 at 14:21
  • My bash script command that generated such error: ... mosquitto_pub -h localhost -t purpleair/lastseenddmmyy -m $lastseenddmmyy .... the $lastseenddmmyy contain "04 Feb 2020". The double quotes are there when I echoed the variable..... When I run it on terminal, it has no problem.... mosquitto_pub -h localhost -t purpleair/lastseenddmmyy -m "04 Feb 2020" .... – bthoven Feb 04 '20 at 14:39