开发者

Hide variable application result from bash output

开发者 https://www.devze.com 2023-01-13 13:37 出处:网络
I am trying to create a script that will run wget to a few sites and check if we receive a 200 OK from the site.

I am trying to create a script that will run wget to a few sites and check if we receive a 200 OK from the site.

My problem is that the result of wget application is shown in the stdout. Is there a way I can hide this.

My current script is:

RESULT=`wget -O wget.tmp http://mysite.com 2>&1`

Later I will use regex to look for the 200 OK we receive from the errout that wget produces. When I run the script, it works fine, but I get the result of the wget added between my 开发者_如何学编程echos.

Any way around this?


You can use:

RESULT=`wget --spider http://mysite.com 2>&1`

And this does the trick too:

RESULT=`wget -O wget.tmp http://mysite.com >/dev/null 2>&1`

Played around a little and came up with that one:

RESULT=`curl -fSw "%{http_code}" http://example.com/ -o a.tmp 2>/dev/null`

This outputs nothing but "200" - Nothing else.


Jack's suggestions are good. I'd modify them just slightly.

If you only need to check the status code, use the --spider option that Jack referenced. From the docs:

When invoked with this option, Wget will behave as a Web spider, which means that it will not download the pages, just check that they are there.

And Jack's second suggestion shows the core ideas behind hiding output:

... >/dev/null 2>&1

The above redirects standard output to /dev/null. The 2>&1 then redirects standard error to the current standard output file descriptor, which has already been redirected to /dev/null, so it won't give you any output.

But, since you don't want output, you might be able to use the --quiet option. From the docs:

Turn off Wget's output.

So, I'd probably use the following command

wget --quiet --spider 'http://mysite.com/your/page'
if [[ $? != 0 ]] ; then
    # error retrieving page, do something useful
fi


TCP_HOST="mydomain.com"
TCP_PORT=80
exec 5<>/dev/tcp/"${TCP_HOST}"/"${TCP_PORT}"
echo -e "HEAD / HTTP/1.0\nHOST:${TCP_HOST}\n" >&5
while read -r line
do
    case "$line" in
        *200*OK* )
            echo "site OK:$TCP_HOST"
            exec >&5-
            exit
           ;;
        *) echo "site:$TCP_HOST not ok"
           ;;
    esac
done <&5
0

精彩评论

暂无评论...
验证码 换一张
取 消