0

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:

  1. Basic auth header is not received on the server side.
  2. 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.

AdminBee
  • 21,637
  • 21
  • 47
  • 71
sumit
  • 101
  • 2
  • The way you're invoking curl is kinda peculiar. Try `curl --user name:password http://www.example.com` instead – Artem S. Tashkinov Jun 24 '20 at 14:33
  • 3
    Does this answer your question? [How can we run a command stored in a variable?](https://unix.stackexchange.com/questions/444946/how-can-we-run-a-command-stored-in-a-variable) – guest Jun 24 '20 at 14:34
  • 2
    The command is not being executed properly (because it's stored in a simple variable). `IFS` causes `'Authorization:`, `Basic`, and `abcdefghijkl'` to be treated as separate arguments. `curl` interprets the last two as urls (they will fail to resolve and account for the two sets of `000`). You could use a function, array, or eval as described in [How can we run a command stored in a variable?](https://unix.stackexchange.com/questions/444946/how-can-we-run-a-command-stored-in-a-variable) – guest Jun 24 '20 at 14:47
  • @guest Yes It does. Thanks. – sumit Jun 24 '20 at 19:04

0 Answers0