0

I am trying to pass the GitHub branch creating API URL as a string into a function to get the status code. But as I tried in many ways, it is not working as I think,

the original URL is :

curl -s -X POST -u [user]:[token] -d '{"ref": "refs/heads/feature/bar", "sha": "'$SHA'"}'  https://api.github.com/repos/$user/$repo/git/refs

what I am trying to do is, taking some part of this URL and passing into a function as a string as follows:

new_branch_creating_url="-X POST -u $username:$password -d '{"'ref'": "'refs/heads/'$new_branch_to_be_created''", "'sha'": ""$old_sha_value""}'  https://api.github.com/repos/$username/$repository_name/git/refs"

My intention is to get the status code of that URL... and for that my function is

#get status code
get_status_code(){
  test_url=$1
  status_code=$(curl -s -I $test_url | awk '/HTTP/{print $2}')
  #echo "status code :$status_code"
  if [ $status_code == 404 ]
  then 
    echo "wrong credentials passed..."
    exit 1
  else
    return $status_code
  fi  
}

and while debugging the code, I am getting like

++ curl -s -I -X POST -u myusername:tokenid -d ''\''{ref:' refs/heads/branch2, sha: '1b2hudksjahhisabkhsd6asdihds8dsajbsualhcn}'\''' https://api.github.com/repos/myusername/myrepo/git/refs
++ awk '/HTTP/{print $2}'

and also my doubt is why sometimes I am received a wrong status code from the function above which I used to get a status code?

while debugging my code:

status_code=
 + '[' == 404 ']'
git_branches.sh: line 154: [: ==: unary operator expected
 + return
 + new_branch_status_code=2
 + echo 'new branch status code ... 2'
new branch status code ... 2
 + '[' 2 == 200 ']'

actually, it is nothing there on status_code from the function, but I received status code =2,,,

not only this time, but I also received 153 instead of 409... why it is like that?

I know this is not a relevant to ask but I have no choice and also it would be very helpful if someone helps me in the early stage of my learning in the shell scripting... thank you...

2

1 Answer 1

2

Instead of curl -s -I, use :

curl -I -s -o /dev/null -w "%{http_code}"

which will give directly http_code.

You don't need awk

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you @Philippe, but while doing this, it will write to a file in the specific path that mentioned, so, there may be chances of utilizing memory for this. correct?
-o /dev/null makes curl to write nothing execpt http_code
Thanks for clarifying, but still not able to understand how to pass my URL into function as a string argument... I referred to some articles mentioned above but was still confused

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.