tags:

views:

526

answers:

4

I'm writing a script to download a bunch of files, and I want it to inform when a particular file doesn't exist.

r=`wget -q www.someurl.com`
if [ $r -ne 0 ]
  then echo "Not there"
  else echo "OK"
fi

But it gives the following error on execution:

./file: line 2: [: -ne: unary operator expected

What's wrong?

+2  A: 

$r is the text output of wget (which you've captured with backticks). To access the return code, use the $? variable.

Andrew Medico
This is the proper method.
kSiR
A: 

$r is empty, and therefore your condition becomes if [ -ne 0 ] and it seems as if -ne is used as a unary operator. Try this instead:

wget -q www.someurl.com
if [ $? -ne 0 ]
  ...

EDIT As Andrew explained before me, backticks return standard output, while $? returns the exit code of the last operation.

Bolo
+2  A: 

Others have correctly posted that you can use $? to get the most recent exit code:

wget_output=$(wget -q "$URL")
if [ $? -ne 0 ]; then
    ...

This lets you capture both the stdout and the exit code. If you don't actually care what it prints, you can just test it directly:

if wget -q "$URL"; then
    ...

And if you want to suppress the output:

if wget -q "$URL" > /dev/null; then
    ...
Jefromi
A: 

you could just

wget ruffingthewitness.com && echo "WE GOT IT" || echo "Failure"

-(~)----------------------------------------------------------(07:30 Tue Apr 27)
risk@DockMaster [2024] --> wget ruffingthewitness.com && echo "WE GOT IT" || echo "Failure" 
--2010-04-27 07:30:56--  http://ruffingthewitness.com/
Resolving ruffingthewitness.com... 69.56.251.239
Connecting to ruffingthewitness.com|69.56.251.239|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: `index.html.1'

    [ <=>                                                                                    ] 14,252      72.7K/s   in 0.2s    

2010-04-27 07:30:58 (72.7 KB/s) - `index.html.1' saved [14252]

WE GOT IT
-(~)-----------------------------------------------------------------------------------------------------------(07:30 Tue Apr 27)
risk@DockMaster [2025] --> wget ruffingthewitness.biz && echo "WE GOT IT" || echo "Failure"
--2010-04-27 07:31:05--  http://ruffingthewitness.biz/
Resolving ruffingthewitness.biz... failed: Name or service not known.
wget: unable to resolve host address `ruffingthewitness.biz'
zsh: exit 1     wget ruffingthewitness.biz
Failure
-(~)-----------------------------------------------------------------------------------------------------------(07:31 Tue Apr 27)
risk@DockMaster [2026] --> 
kSiR