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 保存像curl这样的字符串:(6)无法解析主机.....或HTTP.1.1 200 OK

答案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

相关内容