यदि आप कुछ शीर्षकों से अधिक निकालना चाहते हैं, तो आप सभी शीर्षकों को एक बैश सहयोगी सरणी में रख सकते हैं। यहां एक सरल दिमाग वाला कार्य है जो मानता है कि कोई दिया गया शीर्षलेख केवल एक बार होता है। (Set-Cookie
के लिए यह प्रयोग न करें, नीचे देखें।)
# Call this as: headers ARRAY URL
headers() {
{
# (Re)define the specified variable as an associative array.
unset $1;
declare -gA $1;
local line rest
# Get the first line, assuming HTTP/1.0 or above. Note that these fields
# have Capitalized names.
IFS=$' \t\n\r' read $1[Proto] $1[Status] rest
# Drop the CR from the message, if there was one.
declare -gA $1[Message]="${rest%$'\r'}"
# Now read the rest of the headers.
while true; do
# Get rid of the trailing CR if there is one.
IFS=$'\r' read line rest;
# Stop when we hit an empty line
if [[ -z $line ]]; then break; fi
# Make sure it looks like a header
# This regex also strips leading and trailing spaces from the value
if [[ $line =~ ^([[:alnum:]_-]+):\ *((*[^ ]+)*)\ *$ ]]; then
# Force the header to lower case, since headers are case-insensitive,
# and store it into the array
declare -gA $1[${BASH_REMATCH[1],,}]="${BASH_REMATCH[2]}"
else
printf "Ignoring non-header line: %q\n" "$line" >> /dev/stderr
fi
done
} < <(curl -Is "$2")
}
उदाहरण:
$ headers so http://stackoverflow.com/
$ for h in ${!so[@]}; do printf "%s=%s\n" $h "${so[$h]}"; done | sort
Message=OK
Proto=HTTP/1.1
Status=200
cache-control=public, no-cache="Set-Cookie", max-age=43
content-length=224904
content-type=text/html; charset=utf-8
date=Fri, 25 Jul 2014 17:35:16 GMT
expires=Fri, 25 Jul 2014 17:36:00 GMT
last-modified=Fri, 25 Jul 2014 17:35:00 GMT
set-cookie=prov=205fd7f3-10d4-4197-b03a-252b60df7653; domain=.stackoverflow.com; expires=Fri, 01-Jan-2055 00:00:00 GMT; path=/; HttpOnly
vary=*
x-frame-options=SAMEORIGIN
ध्यान दें कि ऐसा प्रतिक्रिया एक या अधिक कुकी, Set-Cookie
हेडर में शामिल हैं, लेकिन हम केवल देख सकते हैं आखिरी एक क्योंकि बेवकूफ स्क्रिप्ट एक ही शीर्षलेख नाम के साथ प्रविष्टियों को ओवरराइट करता है। (जैसा कि होता है, केवल एक ही था लेकिन हम उसे नहीं जानते।) हालांकि स्क्रिप्ट को विशेष मामले Set-Cookie
पर बढ़ाने के लिए संभव होगा, एक बेहतर दृष्टिकोण शायद कुकी-जार फ़ाइल प्रदान करना होगा, और -b
का उपयोग करना होगा और इसे बनाए रखने के लिए -c
कर्ल विकल्प।
'$ प्रतिक्रिया | ... कर रहा है 'काम नहीं करेगा क्योंकि' $ प्रतिक्रिया' का मान कमांड नहीं है। 'echo $ प्रतिक्रिया' काम करना चाहिए। –