Home > Software engineering >  Can not pass parameter into Curl Command as Bash Script
Can not pass parameter into Curl Command as Bash Script

Time:03-03

Same curl command is not working with bash script. Could anyone ple

Console try (successful one):

curl -ki \
  --cookie cookie-jar.txt \
  --header 'Content-Type: text/xml' \
  --request POST https://testserver:1234/v1/secondarylogin \
  --data '<?xml version="1.0" encoding="UTF-8"?>
<p:secondaryloginrequest xmlns:p="http://www.ericsson.com/em/am/co/authentication/v1_0/">
    <credential>
        <secret>6673</secret>
        <type>otp</type>
    </credential>
    <channelinformation>COMVIVAAGENTAPP</channelinformation>
</p:secondaryloginrequest>' 

**HTTP/1.1 200 OK**
Date: Wed, 02 Mar 2022 10:52:01 GMT
Content-Type: text/xml;charset=utf-8
Date: Wed, 02 Mar 2022 10:52:02 GMT
Set-Cookie: sessionid=default0c07b834d30644e9b30a9bfced82e6f2
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Content-Length: 0

A very simple Bash Script (failed one):

sh sectest.sh 6673

#!/usr/bin/bash
curl -ki \
  --cookie cookie-jar.txt \
  --header 'Content-Type: text/xml' \
  --request POST https://ugtestpo:8446/v1/secondarylogin \
  --data '<?xml version="1.0" encoding="UTF-8"?>
<p:secondaryloginrequest xmlns:p="http://www.ericsson.com/em/am/co/authentication/v1_0/">
    <credential>
        <secret>"$1"</secret>
        <type>otp</type>
    </credential>
    <channelinformation>COMVIVAAGENTAPP</channelinformation>
</p:secondaryloginrequest>'

HTTP/1.1 401 Unauthorized
Date: Wed, 02 Mar 2022 10:47:53 GMT
Content-Type: text/xml;charset=utf-8
Content-Length: 188

I can not pass my secret value with paramatically.

CodePudding user response:

Converting my comment to answer so that solution is easy to find for future visitors.

Following should work for you with proper quoting that allows $1 to expand:

curl -ki \
  --cookie cookie-jar.txt \
  --header 'Content-Type: text/xml' \
  --request POST https://ugtestpo:8446/v1/secondarylogin \
  --data '<?xml version="1.0" encoding="UTF-8"?>
<p:secondaryloginrequest xmlns:p="http://www.ericsson.com/em/am/co/authentication/v1_0/">
    <credential>
        <secret>'"$1"'</secret>
        <type>otp</type>
    </credential>
    <channelinformation>COMVIVAAGENTAPP</channelinformation>
</p:secondaryloginrequest>'

CodePudding user response:

For readability, I'd assign the xml to a variable: heredocs are helpful to avoid quoting hell.

#!/usr/bin/bash

payload=$(cat <<END_XML
<?xml version="1.0" encoding="UTF-8"?>
<p:secondaryloginrequest xmlns:p="http://www.ericsson.com/em/am/co/authentication/v1_0/">
    <credential>
        <secret>$1</secret>
        <type>otp</type>
    </credential>
    <channelinformation>COMVIVAAGENTAPP</channelinformation>
</p:secondaryloginrequest>
END_XML
)

curl -ki \
  --cookie cookie-jar.txt \
  --header 'Content-Type: text/xml' \
  --request POST \
  --data "$payload" \
  https://ugtestpo:8446/v1/secondarylogin
  • Related