Running the code below gives me the error
-bash: [: -ne: unary operator expected
res is ==””. But i thought -ne will compare a string to int. When i do get errors its the above instead of what i want which is the domain name and curls output (its silenced in the first call because it will put junk on stdout). How do i execute the if body?
#!/bin/sh
function test {
res=`curl -I $1 | grep HTTP/1.1 | awk {'print $2'}`
if [ $res -ne 200 ]
then
echo "Error on $1"
curl -I $1
fi
}
test invalidsite.hsdgsdhfgsgdfysgdfgsdfygsyd.com
If
resis an empty string, your condition evaluates to[ -ne 200]which is what the error message is complaining about. Trying to fix this via["$res" -ne 200]won’t work here either, as the empty string is not a number. Do this instead:[ -z "$res" -o "$res" -ne 200 ]. This will first check whether the string is empty (if it is, fail). If it’s not empty, check whether the value is not 200. But this still make bash panic ifresis some non-integer string, so I’d really do a string comparison here:[ -z "$res" -o "$res" != "200" ]Edit: It just occurred to me that you can eliminate the
-zif we’re already doing a string comparison and just go with[ "$res" != "200" ].