Curl -F line break is not interpreted correctly

I am trying to send a notification using pushover using curl in a bash script. I cannot get curl -F to correctly interpret line break.

 curl -s \ -F "token=TOKEN" \ -F "user=USER" \ -F "message=Root Shell Access on HOST \n `date` \n `who` " \ https://api.pushover.net/1/messages.json > NUL 

I tried:

 \n \\\n %A0 

I would rather pass the message directly, and not through the file.

+3
bash terminal curl pushover
May 29 '14 at 12:03
source share
1 answer

curl does not interpret escape screens, so you need to insert the actual newline in the argument that curl sees. In other words, you must get a shell ( bash in this case) to interpret \n , or you need to insert a real new line.

The standard Posix shell does not interpret C escapes as \n , although the standard printf utility command does. However, bash provides a way to do this: in the form of a quote $'...' Resetting the backslash of C will be the interpreter. Otherwise, $'...' acts in the same way as '...' ; therefore, parameter and command replacements are not performed.

However, any shell, including bash , allows you to print newline characters inside quotation marks, and the newline is simply passed through as-is. Therefore, you can write:

 curl -s \ -F "token=$TOKEN" \ -F "user=$USER" \ -F "message=Root Shell Access on $HOST $(date) $(who) " \ https://api.pushover.net/1/messages.json > /dev/null 

(Note: I inserted parameter extensions when they seemed to be missing from the original curl command and changed the deprecated wildcards to the recommended form $(...) .)

The only problem with including newline literal lines, as mentioned above, is that it fills indentation if you care about appearance. Therefore, you can choose the form bash $'...' :

 curl -s \ -F "token=$TOKEN" \ -F "user=$USER" \ -F "message=Root Shell Access on $HOST"$'\n'"$(date)"$'\n'"$(who)" \ https://api.pushover.net/1/messages.json > /dev/null 

This is also a little difficult to read, but it is completely legal. The shell assumes that one argument (β€œword”) consists of any number of quoted or unquoted segments, if there are no spaces between the segments. But you can avoid the multiple-quote syntax by defining a variable that some people consider more readable:

 NL=$'\n' curl -s \ -F "token=$TOKEN" \ -F "user=$USER" \ -F "message=Root Shell Access on $HOST$NL$(date)$NL$(who)" \ https://api.pushover.net/1/messages.json > /dev/null 

Finally, you can use the standard printf utility if you are more used to this style:

 curl -s \ -F "token=$TOKEN" \ -F "user=$USER" \ -F "$(printf "message=Root Shell Access on %s\n%s\n%s\n" \ "$HOST" "$(date)" "$(who)")" \ https://api.pushover.net/1/messages.json > /dev/null 
+4
May 29 '14 at
source share



All Articles