vaj oja
vaj oja

Reputation: 1161

sh script querystring parameter error with curl

I use the following shell script to get the code and mac of the router but always got the wrong result. The mac parameter is placed in front of the url like below.

&mac=00:50:56:2A:E6:20example?code=jd8do0q7

#!/bin/sh
route_code=$(cat /etc/code)
route_mac=`ifconfig eth0|grep eth0|awk '{print $5}'`
curl -o /tmp/updateip --dump-header - "http://example.com?       code=${route_code}&mac=${route_code}"
update_res=`cat /tmp/updateip`
echo ${update_res}

Upvotes: 0

Views: 72

Answers (1)

bgoldst
bgoldst

Reputation: 35314

/etc/code is not a standard Unix file, but its contents are relevant to your question and you haven't specified what those contents are. From your question, I'm guessing it contains jd8do0q7 followed by a carriage return (and possibly followed by a line feed, but that would be stripped off anyway by the $() construct, so we can ignore it), and when you're printing the value of the URL that is being passed to curl (however you're printing it), the carriage return that was picked up by $route_code is moving the cursor back to the start of the line, and so all remaining text overwrites some of the already-printed text, making it incorrectly appear that the &mac=00:50:56:2A:E6:20 text has been placed at the front of the URL.

Ignoring the carriage return for a moment, your URL is being constructed correctly, although I don't know why there seems to be a lot of whitespace between the ? and the code=, and you seem to have made a typo in that mac=${route_code} should probably be mac=$route_mac (also the braces are optional in these cases).

You can test for the presence of a carriage return by printing the URL (you can do this by assigning it to a variable, instead of constructing it inline in the curl command, and then echoing it) and piping it to cat -vet, which shows unprintable characters as printable characters; carriage return will show up as a ^M, line feed as a $.

To remove the carriage return you could edit the file by hand with a text editor (such as vim), pipe it through sed or tr to remove it (e.g. tr -d '\r'), or use any dos-to-unix conversion utility, such as dos2unix that comes with Cygwin (but I don't think you're on Cygwin, as Cygwin/Windows doesn't have ifconfig; it has ipconfig).

If I'm correct in my surmises, then this should work:

#!/bin/sh

route_code=$(cat /etc/code| tr -d '\r')
route_mac=`ifconfig eth0|grep eth0|awk '{print $5}'`
curl -o /tmp/updateip --dump-header - "http://example.com?code=$route_code&mac=$route_mac"
update_res=`cat /tmp/updateip`
echo "$update_res"

Upvotes: 2

Related Questions