Pergunta

In a shell script I am running nslookup on number of URLs

Sometimes some url returns cannot resolv error. I need to capture those errors in a variable.

here is code for nslookup which gets ip address returned

output=$(nslookup "$URL" | grep Add | grep -v '#' | cut -f 3 -d ' ' | awk 'NR>1' )

Now in same variable output, I want to capture the error

nslookup: can't resolve

Stdout I am capturing in a file.

I have tried different version of re-directions - 2>&1 and others but error does not get assigned to variable. I do not want the error to be re-directed to separate file but want it to be recorded in above output variable.

Foi útil?

Solução

As long as you are using awk, you can simplify things considerably

nslookup "$URL" 2>&1 | 
awk -e '/Add/ && !/#/ && NR > 1 {print $2}' 
    -e '/resolve|NXDOMAIN/ { print "error" }'

Where one line has been broken into three for clarity. I cannot reproduce the problem you say you have 2&>1 nor do I believe it should fail.

Outras dicas

The redirection of stderr works when you use

output=$(nslookup "$URL" 2>&1 | grep Add | grep -v '#' | cut -f 3 -d ' ' | awk 'NR>1')

but it is futile since you filter it out immediately with the grep Add. You need to rethink your logic and what you really want. Maybe a better approach is

output=$(nslookup "$URL" 2>&1)
case $output in
   (nslookup:*) ;;
   (*) output=$(echo "$output" | grep Add | ...);;
esac
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top