0

I made a simple "bot" (a one-liner in a cron job) that sends to a chat group some fortunes.

But when the fortune cookie has quotes, the bot just send text until the first quote, then it breaks.

The command currently being draft is:

MSG1=`/usr/games/fortune` ; \
curl -s -X POST -H 'Content-Type: application/json' --data-binary "{\"chat_id\": \"$CHATID\", \"text\": \"${MSG1}\"}" "https://api.chatter1.com/tok/$TOKEN/Message"

I've tried many combinations of single-quote and double-quote, to no avail. I hope you guys could be creative to solve this one-liner.

Thanks.

DrBeco
  • 11,237
  • 9
  • 59
  • 76
  • What happens when you escape the quotes? – Raman Sailopal Feb 10 '21 at 14:23
  • Where? Inside the variable? – DrBeco Feb 10 '21 at 14:23
  • Yeah, MSG1?.... – Raman Sailopal Feb 10 '21 at 14:27
  • 1
    You have to escape the quotes in the variable expansion: `${MSG1//\"/\\\"}` – Benjamin W. Feb 10 '21 at 14:28
  • let me try that @BenjaminW. – DrBeco Feb 10 '21 at 14:28
  • 2
    For a more robust way, you should build a JSON object with a tool such as jq. – Benjamin W. Feb 10 '21 at 14:29
  • Like in https://stackoverflow.com/a/40853190/3266847 – Benjamin W. Feb 10 '21 at 14:30
  • I didn't read the link, but your comment tested ok. Please answer with a one-liner solution and I'll accept your answer! thanks – DrBeco Feb 10 '21 at 14:36
  • 2
    This is not a `curl` problem, but a JSON creation problem. – chepner Feb 10 '21 at 15:20
  • Dear @BenjaminW. please add an answer, a one-liner, with your suggestion, so I can accept the answer. If you don't, as I don't like to have questions without answers here, I'll do it myself later. Thanks a lot. Really helpful. Issue closed. – DrBeco Feb 10 '21 at 20:36
  • I think closing as a duplicate is more appropriate – the other Q&A has a general enough question to cover this use case (even though the specific mistake is different), and there are two answers including quoting and a jq-based one. – Benjamin W. Feb 10 '21 at 22:51
  • I kindly disagree. This one-liner tag is important for me. And as you said, it is a different mistake. After all, doesn't matter what google search brings a new user here, it is better he/she finds a simple answer in a simple question. Easy peasy, not much to read, direct to the point. If you insist in closing as duplicate, then, ok; but please consider giving a short answer and we close with a answer that is much more useful. Thanks – DrBeco Feb 11 '21 at 00:20

1 Answers1

0

Based on a comment, credits to @Benjamin W. :

MSG0=`/usr/games/fortune` ; \
MSG1=${MSG0//\"/\\\"} ; \
curl -s -X POST -H 'Content-Type: application/json' --data-binary "{\"chat_id\": \"$CHATID\", \"text\": \"${MSG1}\"}" "https://api.chatter1.com/tok/$TOKEN/Message"

That works perfectly. Maybe we can improve by avoiding a temporary variable.

Thanks.

DrBeco
  • 11,237
  • 9
  • 59
  • 76