0

I have what I thought was a simple script:

#!/bin/sh

URL=myserver:9443

myCmd="curl -sS -k -X 'POST' 'https://"
myCmd+=$URL
myCmd+="/SKLM/rest/v1/ckms/accessToken' "
myCmd+="-H 'accept: application/json' "
myCmd+="-H 'Accept-Language: en' "
myCmd+="-H 'Content-Type: application/json' "
myCmd+="-d '{ \"userid\": \"SKLMAdmin\", \"password\": \"XXX\" }'"
echo $myCmd

authTok=$($myCmd)

When I run it, I get this:

curl -sS -k -X 'POST' 'https://myserver:9443/SKLM/rest/v1/ckms/accessToken' -H 'accept: application/json' -H 'Accept-Language: en' -H 'Content-Type: application/json' -d '{ "userid": "SKLMAdmin", "password": "XXX" }'

curl: (3) URL using bad/illegal format or missing URL

curl: (6) Could not resolve host: application

curl: (6) Could not resolve host: en'

curl: (6) Could not resolve host: application

curl: (3) URL using bad/illegal format or missing URL

curl: (6) Could not resolve host: "SKLMAdmin",

curl: (3) URL using bad/illegal format or missing URL

curl: (6) Could not resolve host: "XXX"

curl: (3) unmatched close brace/bracket in URL position 1:

}'

If I cut and paste what the echo outputs into the shell, the command works fine, but the line that executes it from within the script gives me that string of errors.

I assume I am violating some basic rule of using cURL within a script, but I cannot seem to figure it out. I need to make the URL a variable (and eventually the username and pwd), and that's where this seems to be breaking down.

4

1 Answer 1

2

Since you have tagged your question with bash I'm assuming you can use bash. In which case you should use bash because it supports arrays. Arrays a much better option for storing commands/command arguments:

#!/usr/bin/env bash

url=myserver:9443
uri='/SKLM/rest/v1/ckms/accessToken'
#data='{ \"userid\": \"SKLMAdmin\", \"password\": \"XXX\" }'
data=$(jo userid=SKLMAdmin password=XXX)

opts=(
    -sSk
    -X POST
    -H 'accept: application/json'
    -H 'Accept-Language: en'
    -H 'Content-Type: application/json'
    -d "$data"
)


authtok=$(curl "${opts[@]}" "${url}${uri}")

The array allows you to expand each individual option separately but as if they were quoted individually in order to prevent word splitting and other unwanted expansions.

"${opts[@]}"

Will expand to:

'-sSk' '-H' 'accept: application/json' '-H' 'Accept-Language: en' '-H' 'Content-Type: application/json' '-d' '{ \"userid\": \"SKLMAdmin\", \"password\": \"XXX\" }'
1
  • Thanks, this got me going! The system I am on doesn't seem to have 'jo', but I was able to work around that manually. Commented May 7 at 17:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .