2015-09-05 67 views
0

我試圖寫一個簡單的腳本來打印前5行的網頁的源代碼,然後把該頁面的請求的時間來加載。目前,我一直在嘗試以下操作:遍歷X線的變量(擊)

#!/bin/bash 
# Enter a website, get data 

output=$(curl $1 -s -w "%{time_connect}\n" | (head -n5; tail -n1)) 
echo "$output"

然而,在一些網頁上,「尾巴」實際上並沒有印刷,這應該是請求的時間,我不知道爲什麼。

我發現我也可以使用while循環來遍歷行並打印整個事物,但是有沒有辦法讓我只回顯變量的前幾行然後是最後一行相同的變量,所以我可以在請求時間前添加一個標題(例如:請求時間:0.489)

我希望能夠把它格式化爲:

echo "HTML: $output\n" 
echo "Request Time: $requestTime"

謝謝!對不起,如果這看起來很簡單,我真的是新的這種語言:)。對我來說,主要的問題是從同一個請求中獲取這些數據 - 執行兩個單獨的捲曲請求將非常簡單。

回答

1

head可能會讀取超過5行的輸入以識別它需要輸出的內容。這意味着您打算傳遞給tail的行可能已被使用。使用單個進程(本例中爲awk)來處理所有輸出更安全。

output=$(curl "$1" -s -w "%{time_connect}\n" | awk 'NR<=5 {print} END {print}) 
0

回車扔我。試試這個:

echo "HTML: " 
retn=$'\r' 

i=0 
while read item 
do 
    item="${item/$retn/}" # Strip out the carriage-return 

    if ((i < 5)); then  # Only display the first 5 lines 
     echo "$item" 
    fi 

    ((i++)) 
    requestTime="$item" # Grab the last line 

done < <(curl $1 -s -w "%{time_connect}\n") 

requestTime="${requestTime##*\>}" # Sanitise the last line 

echo "Request Time: $requestTime"