Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Script dev/tcp/ to variable

Tags:

bash

I'm currently trying to write a simple bash script that connects to my webapi downloads 1 line and uses this line on as a variable. The retrieving itself works just fine:

#!/bin/bash
exec 5<>/dev/tcp/me2stats.eu/5005 # No worries this is a public API ;)
printf "GET /gethighscore?level=1 HTTP/1.1\r\n\r\n" >&5
cat <&5

But I'm having trouble storing the output into a variable, this just outputs a blank line:

output=$(cat <&5)
echo $output

while read line skips the last line (the one I want!):

while read line; do
  echo $line
done <&5

I'm not willing to use wget or curl because I don't want to bloat my docker images even further (they are already around 6GBs).

In short:

How do I store the last line of the http response into a bash variable?

like image 341
Walki Avatar asked Feb 12 '26 07:02

Walki


1 Answers

You need to explicitly close the connection in HTTP/1.1:

#!/bin/bash

exec 5<>/dev/tcp/me2stats.eu/5005 # No worries this is a public API ;)

# Send request
printf "GET /gethighscore?level=1 HTTP/1.1\r\n" >&5
printf "Connection:close\r\n" >&5
printf "\r\n" >&5

# Read response. Use tail to retrieve only the last line.
# But be warned! This is dangerous since you won't be able
# to detect HTTP errors any more. (I suggest to use curl!)
response=$(tail -n1 <&5)

echo "$response"

I admit that /dev/tcp is a nice thing to play with, however any more complex tasks, which might require to parse the http response headers carefully, passing passwords, handling cookies but at least if it comes to https (I think this is clear), http communication should be handled with a dedicated http client program like curl or wget.

Here comes an example with curl:

response=$(curl 'me2stats.eu:5005/gethighscore?level=1')

In opposite to the above /dev/tcp script this command only returns the HTTP response body but not the headers. If you are interested in the headers as well use:

response=$(curl -i 'me2stats.eu:5005/gethighscore?level=1')
like image 116
hek2mgl Avatar answered Feb 17 '26 05:02

hek2mgl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!