I am trying to send a google chat message using bash script. When I define a local variable or using simple text, it works. But when I source a file, and use variables defined in that file, I get error.
This works:
#!/bin/bash
MSG="Data"
curl -H 'Content-Type: application/json' -X POST "$CHAT_URL" --data @<(cat <<EOF
{
"cards": [
{
"sections": [
{
"widgets": [
{
"textParagraph": {
"text": "Msg: $MSG"
}
}]}]}]}
EOF
)
This does not:
#!/bin/bash
source file.txt # contents: MSG=Data
echo $MSG # variable defined in file.txt
curl -H 'Content-Type: application/json' -X POST "$CHAT_URL" --data @<(cat <<EOF
{
"cards": [
{
"sections": [
{
"widgets": [
{
"textParagraph": {
"text": "Msg: $MSG"
}
}]}]}]}
EOF
)
Output:
Data
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Closing quote expected in string.\n\n^",
"status": "INVALID_ARGUMENT"
}
}
This question is basically a duplicate of Are shell scripts sensitive to encoding and line endings? and Are multi-line strings allowed in JSON?
Your file has windows line endings (\r\n
). Therefore the string loaded from your file ends with \r
. JSON strings are not allowed to contain control characters, hence the error message.
To fix the problem, convert your file using dos2unix file.txt
.