Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wget with errorlevel bash output

Tags:

linux

bash

centos

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

like image 970
CyberK Avatar asked Nov 07 '10 17:11

CyberK


2 Answers

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

like image 132
ojblass Avatar answered Nov 13 '22 11:11

ojblass


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" [email protected]
  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 :)

like image 24
Tim Post Avatar answered Nov 13 '22 11:11

Tim Post