curl return HTTP code 503 when called from a script

17,010

Solution 1

It was a proxy problem. If I use curl -v .... I can see the following output:

When curl is typed directly in terminal I have :

* About to connect() to localhost port 80 (#0)
*   Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 80 (#0)

And when I used it into a bash script I get :

* About to connect() to proxy proxy.my.company port xxx (#0)
*   Trying xx.xx.xx.xx... connected
* Connected to proxy.my.company (xx.xx.xx.xx) port xxx (#0)

So to fix it I added this in the top of my script :

export no_proxy=localhost,127.0.0.1
export http_proxy=""

I am very surprised to have to do this, because I already have an environment var no_proxy who already reference localhost and 127.0.0.1

Solution 2

Try to run it as bash -x script.sh.

Share:
17,010
PierreF
Author by

PierreF

Updated on June 27, 2022

Comments

  • PierreF
    PierreF almost 2 years

    I'm try to call some REST API and get the resulting HTTP code using curl. If in a terminal I type :

    curl -s -o /dev/null -I -w '%{http_code}' -X POST 'http://localhost/gitlab/api/v3/projects?private_token=my_private_token&name=blabla' -H 'Content-Length: 0'
    

    It works and return me the HTTP code 201 ("created"). Now I try to use this command in a bash script replacing a part of the url with variable:

    echo "Enter base URL :"
    read gitlab_url # Here I type 'http://localhost/gitlab', to generate the same URL as in first code snippet
    code_status=$(curl -s -o /dev/null -I -w '%{http_code}' -X POST '$gitlab_url/api/v3/projects?private_token=my_private_token&name=blabla' -H 'Content-Length: 0')
    echo "$code_status"
    

    And then it returns me the HTTP code 503 ("Service Unavailable"). To see if there is any differences between the "hard coded" URL and the generated one, I do :

    echo "curl -s -o /dev/null -I -w '%{http_code}' -X POST '$gitlab_url/api/v3/projects?private_token=my_private_token&name=blabla' -H 'Content-Length: 0'"
    # Output :
    curl -s -o /dev/null -I -w '%{http_code}' -X POST 'http://localhost/gitlab/api/v3/projects?private_token=my_private_token&name=blabla' 'Content-Length: 0'
    

    And if I execute this in a terminal directly, it works and return me 201. So: why do this command fails if I use it in a script ? Is there anything I missed ?

  • PierreF
    PierreF almost 10 years
    The bash -x didn't helped me, but the idea of using debug mod (on curl) helped. Thx