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?
$r
is empty, and therefore your condition becomesif [ -ne 0 ]
and it seems as if-ne
is used as a unary operator. Try this instead:EDIT As Andrew explained before me, backticks return standard output, while
$?
returns the exit code of the last operation.$r
is the text output of wget (which you've captured with backticks). To access the return code, use the$?
variable.I been trying all the solutions without lucky.
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:
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.
you could just
Best way to capture the result from wget and also check the call status
This way you can check the status of wget as well as store the output data.
If call is successful use the output stored
Otherwise it will exit with the error wget failed
Others have correctly posted that you can use
$?
to get the most recent exit code: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:
And if you want to suppress the output: