I am trying to run a dynamically generated curl
command with basic authorization headers and store response code in a variable.
below is my shell script. (say test.sh
)
auth="--header 'Authorization: Basic abcdefghijkl'"
url="http://localhost:8080"
cmd="curl -s -o /dev/null -I -w "%{http_code}" -X GET ${url} ${auth}"
echo $cmd
code=$($cmd)
echo $code
but above command doesn't send the authorization header in the GET request.
To demonstrate it I have written a small nodejs http server and logging headers in it, see below.
var http = require('http');
http.createServer(function (req, res) {
console.log(req.headers);
res.write('This is a sample response from server.\n');
res.end();
}).listen(8080);
console.log("Server is listening on port 8080");
but on running test.sh
via
bash test.sh
I get below output in shell:
"200""000""000"
and on server side i get below text in logs.
{ host: 'localhost:8080', 'user-agent': 'curl/7.54.0', accept: '*/*' }
There are two problems:
- Basic auth header is not received on the server side.
- Instead of 200 status-code I get
"200""000""000"
which is unexpected.
Can you please suggest what am i missing here?
Thanks in anticipation.
Try
– Artem S. Tashkinov Jun 24 '20 at 14:33curl --user name:password http://www.example.com
insteadIFS
causes'Authorization:
,Basic
, andabcdefghijkl'
to be treated as separate arguments.curl
interprets the last two as urls (they will fail to resolve and account for the two sets of000
). You could use a function, array, or eval as described in How can we run a command stored in a variable? – guest Jun 24 '20 at 14:47