I want to send the contents of a file after a given line number to Slack using curl. I’d like it to be formated as code after some message. ChatGPT is failing to help here. The code I’m using is:
log_text=$(awk -v n="$some_number" 'NR >= n' "$log_file" )
# Handle line breaks and special characters:
#log_text=$(printf '%s' "$log_text" | jq -Rs .) # Doesn't work
#log_text=$(printf '%s' "$log_text" | sed 's/"/\"/g; s/$/\n/' | tr -d 'n') # Also doesn't work
log_text=$(echo "$log_text" | jq -R -s -c) # Doesn't work as well
echo "============================"
echo "$log_text"
echo "============================"
curl -s -f --retry 2 -X POST -H 'Content-type: application/json' --data "{"text": " some text here ```$log_text``` "}"
"$slack_hook" || echo "Failed to send message"
This always fails to send the message. If I set log_text=""
then it works correctly, so I’m assuming it’s some problem with the formatting of the content in log_text
. The file has several special characters line breaks and so on, but I’d like to send it neatly on the json so it can be read on Slack. What is going on here?
3
Answers
What ended up working (not sure why):
First duplicate slashes, then replace all newline characters with 'n':
Then use a variable to create the whole payload, so it's easier to debug:
Finally send the message:
I would recommend avoiding using a template builder within the curl command and instead using a single argument.
Instead:
You can do something like:
In this case, you can print
$log_text_2
to gain some insights on what went wrong. I think there may be some escape characters causing the issue.Something ChatGPT will never do for you is write working code with explanations so you learn something
cat sendlog.sh
:Example sending content of
somefile.log
starting at line 42: