1

In PHP or Python, for example, you cand do curl and receive a object with all properties organized.

In bash I have to invoke curl application.

I need to get status code and content in same command (its obvious because the status code is relationed with success or not to get content). But how I can do this?

I am trying this:

# get url in function
urlcurl=$(echo $@)
# create new file descriptor and redirect to STDOUT
exec 3>&1
# get curl status code and store in curlstatuscode
curlstatuscode=$(curl -L -k -w "%{http_code}" -o >(cat >&3) --silent \"${urlcurl}\")

My problem is about content: When I execute this in terminal I receive content in STDOUT (that is the command had to do). But I am trying to store this STDOUT using regular redirect expressions and they not work.

One example:

exec 3>&1
HTTP_STATUS=$(curl -k --silent -L -w "%{http_code}" -o >(cat >&3) 'http://example.com')
echo $HTTP_STATUS

If you not understood what I am trying to do, roughly mode (and invalid) would be something like that: (I know that is invalid, I only want to clarify)

HTTP_CONTENT=$(echo `HTTP_STATUS=$(curl -k --silent -L -w "%{http_code}" -o >(cat >&3) 'http://example.com'`)

HTTP_CONTENT will get get content and HTTP_STATUS will get curl status code.

Please do not say to user another language. I need to solve this in bash. Is very simple to do that in other languages (mainly oriented objects). I really want to do this in bash.

Thank you!

1 Answer 1

1

Since http status is the last line in curl output, you can do like this in BASH:

out=$(curl -k --silent -L -w "\n%{http_code}" 'minecraft.net/haspaid.jsp?user=apterixbr')
http_status="${out##*$'\n'}"
http_content="${out%$'\n'*}"
Sign up to request clarification or add additional context in comments.

5 Comments

worked in part. if I get no content (like when you get timedout), http_status and http_content will be empty. http_content is OK to be empty, but http_status had to be timedout code.
One way is use -o option after 'example.com' to write in file, but I do not want provoke write in storage without really need this.
other test failed: sometimes status code will not be in last line. example: curl -k --silent -L -w '%{http_code}' 'minecraft.net/haspaid.jsp?user=apterixbr'
Check updated answer. "\n%{http_code}" will ensure one newline before status code.
now worked as a charm. thank you! hope the best for you :)

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.