1

$RESPONSE variable does not being displayed in if block. In my code i have commented exactly where

#!/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

Any ideas how to pipe $RESPONSE text with? $RESPONSE holds string like curl: (6) Could not resolvehost ..... or HTTP.1.1 200 OK

1

Your script actually works. Are you sure your sites.txt is correct? For example, I tried with:

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

I saved your script as foo.sh, and running it on the file above gives:

$ 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

By the way, as you can see above, it fails for yahoo.com which is redirecting. Perhaps a better way would be to use ping to check. Something like this (including some other general improvements):

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

If you really do need the status, use:

#!/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
  • Hmmm strange.Can it be then rasberry pi issue? maybe bash does not read it somehow? – Mindau Mar 10 '17 at 19:18
  • anyway your solution is way better with ping at it works as expected – Mindau Mar 10 '17 at 19:25
  • @Mindau are you 100% sure you're actually using bash? You didn't mention anything about raspberry. Are you sure you aren't using sh instead of bash, or even some sort of busybox shell? – terdon Mar 10 '17 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.