Bash スクリプト $variable コンテンツが空であることを示します。

Bash スクリプト $variable コンテンツが空であることを示します。

$RESPONSE変数はifブロックには表示されません。私のコードでは、私は正確にコメントしました。

#!/bin/bash

TIME=`date +%d-%m-%Y:%H:%M:%S`
cat sites.txt | while read site
do
    URL="http://$site"
    RESPONSE=`curl -I $URL | head -n1`
    echo $RESPONSE #echo works
    if echo $RESPONSE | grep -E '200 OK|302 Moved|302 Found' > /dev/null;then
        echo "$URL is up"
    else
        #$RESPONSE variable empty. Returns [TIME] [URL] is DOWN. Status:
        echo "[$TIME] $URL is DOWN. Status:$RESPONSE" | bash slackpost.sh
    fi  
done

$RESPONSEテキストをパイプする方法についてのアイデアはありますか? $RESPONSE はカールのような文字列を保持します: (6) ホストをチェックできません....

ベストアンサー1

スクリプトが機能します。あなたがsites.txt正しいと確信していますか?たとえば、次のように試しました。

$ cat sites.txt 
google.com
unix.stackexchange.com
yahoo.com

スクリプトをとして保存しfoo.shて上記のファイルから実行すると、次のようになります。

$ foo.sh 2>/dev/null
HTTP/1.1 302 Found
http://google.com is up
HTTP/1.1 200 OK
http://unix.stackexchange.com is up
HTTP/1.1 301 Redirect
[10-03-2017:20:49:29] http://yahoo.com is DOWN. Status:HTTP/1.1 301 Redirect

ところで、上に見られるようにリダイレクトされるyahoo.comでは失敗します。おそらくより良い方法はpingを使用して確認することです。次のもの(他の一般的な改善点を含む):

while read site
do
    if ping -c1 -q "$site" &>/dev/null; then
        echo "$site is up"
    else
        echo "[$(date +%d-%m-%Y:%H:%M:%S)] $site is not reachable."
    fi  
done < sites.txt

状態が本当に必要な場合は、次を使用します。

#!/bin/bash

## No need for cat, while can take a file as input
while read site
do
    ## Try not to use UPPER CASE variables to avoid conflicts
    ## with the default environmental variable names. 
    site="http://$site";
    response=$(curl -I "$site" 2>/dev/null | head -n1)
    ## grep -q is silent
    if grep -qE '200 OK|302 Moved|302 Found|301 Redirect' <<<"$response"; then
        echo "$site is up"
    else
        ## better to run 'date' on the fly, if you do it once
        ## at the beginning, the time shown might be very different.
        echo "[$(date +%d-%m-%Y:%H:%M:%S)] $site is DOWN. Status:$response" 
    fi  
done < sites.txt

おすすめ記事