开发者

wget with errorlevel bash output

I want to create a bash file (.sh) which does the following:

I call the script like ./download.sh www.blabla.com/bla.jpg

the script has to echo then 开发者_StackOverflow社区if the file has downloaded or not...

How can I do this? I know I can use errorlevel but I'm new to linux so...

Thanks in advance!


Typically applications in Linux will set the value of the environment variable $? on failure. You can examine this return code and see if it gets you any error for wget.

#!/bin/bash
wget $1 2>/dev/null
export RC=$?
if [ "$RC" = "0" ]; then
   echo $1 OK
else
    echo $1 FAILED
fi

You could name this script download.sh. Change the permissions to 755 with chmod 755. Call it with the name of the file you wish to download. ./download.sh www.google.com


You could try something like:

#!/bin/sh

[ -n $1 ] || {
    echo "Usage: $0 [url to file to get]" >&2
    exit 1
}

wget $1

[ $? ] && {
  echo "Could not download $1" | mail -s "Uh Oh" you@yourdomain.com
  echo "Aww snap ..." >&2
  exit 1
}

# If we're here, it downloaded successfully, and will exit with a normal status

When making a script that will (likely) be called by other scripts, it is important to do the following:

  • Ensure argument sanity
  • Send e-mail, write to a log, or do something else so someone knows what went wrong

The >&2 simply redirects the output of error messages to stderror, which allows a calling script to do something like this:

foo-downloader >/dev/null 2>/some/log/file.txt

Since it is a short wrapper, no reason to forsake a bit of sanity :)

This also allows you to selectively direct the output of wget to /dev/null, you might actually want to see it when testing, especially if you get an e-mail saying it failed :)


wget executes in non-interactive way. This means that wget work in the background and you can't catch de return code with $?.

One solution it's to handle the "--server-response" property, searching http 200 status code Example:

wget --server-response -q -o wgetOut http://www.someurl.com
sleep 5
_wgetHttpCode=`cat wgetOut | gawk '/HTTP/{ print $2 }'`
if [ "$_wgetHttpCode" != "200" ]; then
    echo "[Error] `cat wgetOut`"
fi

Note: wget need some time to finish his work, for that reason I put "sleep 5". This is not the best way to do but worked ok for test the solution.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜