Click here to Skip to main content
15,041,266 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to shell scripting and MQTT.
I need to publish a `JSON file` using `MQTT`. We can do it by storing the JSON contents in a `shell variable` and then using it in MQTT publish command. But it is not working for me.

Please help me out to get the output. Whether I need to add some more code in the shell script. I don't know how to proceed.

What I have tried:

my shell script:
```var1="{"name":"Harini", "age":24, "city":"NewYork", "message":"Hello world"}"```

my Mosquitto commands:
```mosquitto_pub -h localhost -t "test" -m {\"Contents\":$var1}```
```mosquitto_sub -h localhost -t "test"```

Output I got:
Expected Output:
```{"Contents":{"name":"Harini", "age":24, "city":"NewYork", "message":"Hello world"}}```
Updated 8-Jun-21 7:07am

1 solution

I think the outer enclosing set of double quotes in your var1=.... statement might need to be single quotes (I assume the triple-quotes are just there for show and not what you actually typed). I have no familiarity with mosquitto but have had a few wrestling matches with shell syntax over the year . . . using "echo" as a mosquitto substitute fixed it for me . . .

var2='{"name":"Harini", "age":24, "city":"NewYork", "message":"Hello world"}'
echo {\"Contents\":$var2}
{"Contents":{"name":"Harini", "age":24, "city":"NewYork", "message":"Hello world"}}

var3="{"name":"Harini", "age":24, "city":"NewYork", "message":"Hello world"}"
bash: world}: command not found...
echo $var3

Might possibly be shell-dependent (I was using bash).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900